Главная » Просмотр файлов » 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), страница 11

Файл №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) 11 страница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СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Thefirst is the location of the MBM Graphics files – again note we’re usingelements that are defined previously, keeping this code as portable aspossible. The first 0 is a write protect flag. If it is 0, we cannot edit thegraphic (if it is 1, we can). Unless you have a need to change a graphicpermanently, you should always leave this as 0.Finally, the last number lets the command know which bitmap to load.As an .mbm file holds multiple bitmaps (hence MBM), we need to stateexplicitly which one we’re looking at, as a graphics window can onlyhold one bitmap graphics.

The first bitmap in any .mbm file is number 0,followed by number 1, 2, 3, etc.Putting the Procedures TogetherPROC Init: has a lot of little things going on that all need to be doneevery time a program is opened. Here’s all the bits put together in thefinal procedure. Hopefully you can follow this all now:PROC Init:LOCAL FirstRun%,Drive$(1),Foo%SETFLAGS &10000rem Used to allow Auto Switch offGIPRINT KAppName$+", "+KAuthorName$+", ver "+KAppVer$rem *** Set some names and pathsMbmFile$="Core.mbm" : Data$="\System\Apps\Core\"Foo%=ASC("y")DODrive$=UPPER$(CHR$(Foo%))IF EXIST(Drive$+":"+Data$+MbmFile$)48EVENT COREPath$=Drive$+":"+Data$BREAKENDIFFoo%=Foo%-1UNTIL CHR$(Foo%)="Y"IF Path$=""ALERT("Support mbm file not found","Please re-install"+KAppName$)STOPENDIFrem *** INI File HandlingFirstRun%=LoadIniFile%:rem *** Screen dimensions, color fixed across all devicesScreenWidth%=gWIDTH : ScreenHeight%=gHEIGHTIF ScreenWidth%=640 AND ScreenHeight%=200rem Series 80 CommunicatorsPlatform%=KPlatformSeries80%ScreenMenubarOffset%=0ScreenMainViewWindowOffset%=20ScreenStatusBarHeight%=0ScreenLeftOffset%=0ScreenRightOffset%=0ELSEIF ScreenWidth%=176 AND ScreenHeight%=208rem Series 60Platform%=KPlatformSeries60%ScreenMenubarOffset%=0ScreenMainViewWindowOffset%=44ScreenStatusBarHeight%=20ScreenLeftOffset%=0ScreenRightOffset%=0ELSEIF ScreenWidth%=208 AND ScreenHeight%=320rem UIQPlatform%=KPlatformUIQ%ScreenMenubarOffset%=24ScreenMainViewWindowOffset%=44ScreenStatusBarHeight%=18ScreenLeftOffset%=0ScreenRightOffset%=0ELSErem Any new platforms will default to a full screen viewPlatform%=KPlatformGeneric%ScreenMenubarOffset%=20ScreenMainViewWindowOffset%=0ScreenStatusBarHeight%=0ScreenLeftOffset%=0ScreenRightOffset%=0ENDIFCanvasWidth%=ScreenWidth%-ScreenLeftOffset%-ScreenRightOffset%CanvasHeight%=ScreenHeight%-ScreenMainViewWindowOffset%ScreenStatusBarHeight%rem *** Create initial windowsId%(9)=gLOADBIT(Data$+MbmFiles$,0,0)Id%(KMainViewWindow%)=gCREATE(0,KMainViewWindowOffset%,CanvasWidth%,CanvasHeight%,1,KDefaultWin4kMode%)ENDPOTHER PROCEDURES493.3 Other Procedures3.3.1The InitApp: (Initialize this Application) ProcedurePROC Init: is a generic routine.

It will very rarely change when youstart a new program. Apart from the layout of windows and graphics thatyou will load in, it will stay static. The second initialize routine, PROCInitApp:, will be very program-dependent, as it covers anything thatneeds to be set up for your specific program.In Event Core, we have a small InitApp: that simply displays onegraphic on the screen and some text. As we’ll see, other programs canget quite involved in the InitApp:, so again it needs careful planning.Here’s the plain English version of our Event Core procedure:PROC InitApp:Start using to the main drawable windowShow the graphic we’ve loadedPrint some textENDPFor this procedure, let’s look straight at the OPL code:PROC InitApp:gUSE Id%(KMainViewWindow%)gFONT KOplFontLatinPlain12&gAT 0,CanvasHeight%/2gPRINTB "OPL Event Core",CanvasWidth%,3gAT 0,(CanvasHeight%-20)IF Platform%=KPlatformGeneric% : gPRINTB "GenericMachine",CanvasWidth%,3ELSEIF Platform%=KPlatformSeries80% : gPRINTB "Series 80Communicator",CanvasWidth%,3ELSEIF Platform%=KPlatformSeries60% : gPRINTB "Series 60Device",CanvasWidth%,3ELSEIF Platform%=KPlatformUIQ% : gPRINTB "UIQDevice",CanvasWidth%,3ENDIFrem *** Displaying an MBM (loaded in PROC Init:)gAT (CanvasWidth%-127)/2,(CanvasHeight%-65)gCOPY Id%(9),0,0,127,41,3ENDPWe can have more than one drawable window open, and only one canbe active at a time.

It is important to make sure that we’re using the rightone. The gUSE command takes the values that we used when using thegCREATE command to identify the windows, in this case the constantrepresenting the Main Window:gUSE Id%(KMainViewWindow%)50EVENT COREThe numbers in the gCOPY statement tell OPL which part of a graphicalbitmap to copy to the screen. We’ll discuss these numbers and bitmapsin more detail in Chapter 5.

Next are three new commands that give youmuch more control when printing text onto the screen.gFONT allows you to change the font of any text that is printed after thiscommand is read. Values for the available fonts are held in the Const.ophfile, so you can use these names rather than the numbers:FontValueLatinLatinLatinetc.KOplFontLatinPlain12&KOplFontLatinBold12&KOplFontLatinItalic12&etc.In any editing application (such as the text editor you are using) there isa flashing cursor to show where the next character will appear. OPL hastwo cursors. One for text using the PRINT commands, and one graphicalcursor.

gAT affects the graphical cursor operations. It starts at (0,0) whenyou first create a window. You move it by simply stating where youwould like it to go with:gAT (X%,Y%)where (0,0) is the top left corner of the current window. In our PROCInitApp: for Event Core we again use the numbers worked out previously for screen dimensions. This is why they were created as GLOBALvariables, so they could be used in different procedures.gPRINTB is short for Graphical Print Banner:gPRINTB Text$,Width%,Alignment%It takes the cursor as the bottom left of the banner strip it will print thecontents of Text$ in. This banner has a specified width (Width%) andcan be left, center or right justified using the Alignment% variable: seeFigure 3.5.AlignmentRightLeftCenterValueConstant123KDTextRight%KDTextLeft%KDTextCenter%So in our Event Core example:gPRINTB "OPL Event Core",CanvasWidth%,KDTextCenter%OTHER PROCEDURES51Figure 3.5 gPrintB spaces and line upwe are printing the text "OPL Event Core" centrally inside our banner,which is the width of our main screen.The IF statement has a colon right after it, then another OPL command.Why are these not over two lines? Well, there’s no reason to not havethem over two lines.

The following is also correct:IF Platform%=KPlatformGeneric%gPRINTB "Generic Machine",CanvasWidth%,3ELSEIF Platform%=KPlatformSeries80%gPRINTB "Series 80 Communicator",CanvasWidth%,3etc....But there are times when it is easier to lay out code with more than onestatement on a line. You can concatenate statements using a colon, witha space on either side of it. So this is also correct:IF Platform%=KPlatformGeneric% : gPRINTB "GenericMachine",CanvasWidth%,3ELSEIF Platform%=KPlatformSeries80% : gPRINTB "Series 80Communicator",CanvasWidth%,3etc....3.3.2The Main DO. .

.UNTIL LoopLet’s look back at our pseudo-OPL for the main procedure:PROC Main:GLOBAL rem We’ll fill these in as we plan the program52EVENT CORELOCAL rem We’ll fill these in as we plan the programInit:InitApp:DOrem Get a key press (an event)rem Act on this key pressUNTIL rem we need to exit the programExit:ENDPNow we have everything set up, variables loaded, and the main screenshowing what we want it to show, we can start doing the central loopof our program. The DO...UNTIL loop will have the program iteratethrough the ‘get an event, act on event’ cycle until we want to exit theprogram. As the program reacts to those events, things will happen.Before we look at those events, let’s look at how we get out of the loopfirst.

For this, we’ll need to set up some error trapping.Error Trapping in OPLWe’re going to base this loop (and exiting the loop) around error trapping.We’ve already seen (when loading the INI database file) how to TRAP anerror so that a program does not display an error message and stop. Whatwe are going to do now is give the program specific instructions on whatto do if there is an error, rather than just simply stop.Firstly, we’ll need to know when an error has occurred.

We do this bycreating a LOCAL variable (we’ll use E in Event Core) and letting it equalthe last error OPL knows about (normally zero for no error).Next, what to do when an error occurs? This is where the ONERRcommand comes in. After using ONERR we must tell the program to jumpsomewhere in the procedure that the ONERR command is. How do wedo this? We use the GOTO command.GOTO immediately jumps the flow of the program from where it is toanother line that is labeled with a given name. It is especially useful inthe error handling routine as it forces the program to go where we needit, no matter where it is when the error happens.So at the top of our PROC Main: let’s set up this error handlingmechanism:LOCAL EE=ERR : ONERR OFFONERR Error::To be safe, we switch all the existing error trapping off (using ONERR OFF)before we set up our own error handler.

In this case, when there is anerror, we’ll jump to a label called Error:: [note that all labels end witha double colon (::)].OTHER PROCEDURES53So after all our code in PROC Main: we need to add the followingcode:Error::rem *** Show what the error isdINIT "Error"dTEXT "",ERRX$,KDTextCenter%dTEXT "",ERR$(ERR),KDTextCenter%dBUTTONS "Done",KdBUTTONEnter%LOCK ON :DIALOG :LOCK OFFGOTO Top::This brings in one of the main OPL ‘widgets’.

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

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

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

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