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

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

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

This is where the INI file comes in.The INI file is a very small database that holds information important tothe program. If you think of a database as being a large stack of cards, theINI file is represented by one card, which looks a bit like the illustrationin Figure 3.4.Figure 3.4 Index card with three variablesAs with all databases, you have a label (on the left) and the value(on the right).

Note how similar this is to assigning a value to a variable.Databases are just big ways to store variables on the disk when a programis not running.We illustrate the concept of an INI file in Event Core by saving onevalue – later examples (see Chapter 6) will create much larger databasesthat we can manipulate, but for now, we’ll use the simplest databasepossible.So how do we open and read our INI file? As always, think about thesteps in English first:• is there an INI file already? If there is, read the values• if there isn’t, create a set of default values.In fact, we’ll change that last line very slightly to read:• if there isn’t, create a set of default values, then save those values to anew INI file.So we’ll also need a way to save the values when any of them arechanged, and when we exit our program. There are two main operationsin these statements; reading the values in the INI file; and saving theINI file.

Creating the INI file will only ever be done if the reading fails,so is part of that procedure. Let’s put this into something a bit likeOPL code:PLANNING THE EVENT CORE, Init:41PROC LoadIniFile%:IF there is an INI fileRead the values into memoryELSECreate some default values in memorySave these values (call PROC SaveIniFile%: to avoid duplicatingcode)ENDIFENDPPROC SaveIniFile%:Delete any existing INI fileCreate an empty database cardWrite the values on the database cardSave the database card to storageENDPNote the % at the end of the procedure names.

This is because when weare finished, we will RETURN a value to the procedure that called thesetwo procedures. The RETURN keyword allows your procedure to passback some kind of result to whichever other procedure called it. Much likevariables, the type of the result you pass back is specified in the procedurename – so PROC ReturnsString$:, PROC ReturnsLongInt&, PROCReturnsShortInt% or PROC ReturnsFloat are all valid names.

Yousimply then use RETURN to pass back the information you want. CallingRETURN brings the execution of that procedure to an end, much like asif ENDP had been reached. Here, if the INI file exists, we will return avalue of 0, if we have to create a new INI file, then we will RETURN avalue of 1. If we’ve had to create the INI file, we can assume that this isthe first time the program has been run. So in PROC Init: we load theINI file with:FirstRun%=LoadIniFile%:This way, FirstRun% takes on the value of whatever we RETURN inLoadIniFile%:.You’ve already seen how we look for a file when looking for the.mbm file, so you should recognize the IF statement that looks for theINI file:PROC LoadIniFile%:IF EXIST ("C:"+Data$+KAppNameShort$+".ini")OPEN "C:"+Data$+KAppNameShort$+".ini",A,SoundVol%SoundVol%=A.SoundVol%CLOSE A42EVENT CORERETURN 0ELSErem Set initial values here, then save to diskSoundVol%=0SaveIniFile%:RETURN 1ENDIFENDPSo let’s look first at what happens if the INI file exists.

Well, the first thingto do is OPEN the database with the OPEN command, which is laid outlike this:OPEN Filename, Reference, Variable1, Variable 2, Variable 3, etc.The filename is constructed as before (and again note we use the constantstring that holds the name, not the name itself).It is possible to have more than one database open at a time, so wegive each open database a reference letter. In this case, we’ve used theletter "A". In OPL, you can use the letters A to Z to reference databases.Finally, we need to know how the database is made up, by listing allthe variables that are on the card.

In the INI file, we’ll only have onevariable, but you can have up to 32. Think of these as the heading namesof each field of your database.OPEN "C:"+Data$+KAppNameShort$+".ini",A,SoundVol%Thus our INI file has one variable (SoundVol%) and is reference letter "A".We can then read the values stored in the database by using thereference letter, followed by a dot, followed by the name of the field. Sowe can copy the database value of SoundVol% to our GLOBAL variableSoundVol% with the following:SoundVol%=A.SoundVol%That’s us finished with the database! As with anything in programming,when you’re finished with something, close it, put it away, or destroy it.Here we CLOSE the database with reference "A" and RETURN the value 0,leaving the procedure.CLOSE ARETURN 0What if the INI file doesn’t exist? Well, we set a default value to theGLOBAL variable SoundVol% and call PROC SaveIniFile%:PLANNING THE EVENT CORE, Init:43SoundVol%=0SaveIniFile%:RETURN 1When we come back from PROC SaveIniFile%: we RETURN the valueof 1, representing the fact that we had to create a new INI file.Now let’s think about the SaveIniFile%: procedure in English:• if the directory doesn’t exist, create it• if there is already an INI database with old values, then delete it• create a new INI database• save the values to the database• close the database.And now in pseudo-OPL:PROC SaveIniFile%:Make Directory "C:"+Data$Delete the database "C:"+Data$+KAppNameShort$+".ini" if neededCreate a new database in the same locationSave the SoundVol% value to the databaseClose the databaseENDPFinally, here it is in OPL:PROC SaveIniFile%:TRAP MKDIR "C:"+Data$TRAP DELETE "C:"+Data$+KAppNameShort$+".ini"TRAP CREATE "C:"+Data$+KAppNameShort$+".ini",A,SoundVol%A.SoundVol%=SoundVol%APPENDCLOSE AENDPThis introduces us to a new concept – error handling.

Normally, whenan error happens on running an OPL program, the program will stop anddisplay an error message. The TRAP command will trap or suppress anyerror messages that occur due to a line of code that follows it, allowingthe program to continue running. The reason we do this when we MKDIR(Make a Directory) is that there is every chance the directory will alreadybe there, but if this is the first time we are running the program, it won’tbe there. This way, if it is not there, we will make the directory, if not,then the program will raise an error, it will get TRAPped and we canmove on and ignore it.44EVENT COREThe same reasoning is used for deleting the existing INI file. If therewas no INI file and we tried to DELETE it, then we would have an errormessage. TRAPping again lets us carry on.The CREATE database command is identical in layout to the OPENdatabase command.

We supply a filename, a reference letter, and a listof variable names.To assign a variable’s value from our program variables to one in thedatabase is simple; we just use the reference letter and the name of thefield:A.SoundVol%=SoundVol%However, all we’ve done is assign values. We haven’t actually writtenthem into the database yet.

Once we’ve assigned all the values, we needto create a record (like a paper index card) and add that record into theempty database (e.g. a large empty filing box). This is where the APPENDcommand comes in:APPENDThis adds the record we have just created (with A.SoundVol%=SoundVol%) to the end of the database. Of course, because we’vedeleted any existing database and created a new database, this appendedrecord will become the first (and only) record.As before when loading the INI database file, when we’re finished weclose the database, again with the appropriate close command:CLOSE ASorting out Screen SizesWindows are a bit like pieces of paper on (and off) the screen. If we wantto show something on the screen, we need to write it on one of thesepieces of paper. We’re going to look at windows and graphics in a laterchapter, but here are some basics.When an OPL program is started, it creates a default window.

Thiswindow fills the screen, so we can use this window to get the size ofthe screen of the phone we are running on. It is also made the currentwindow; the current (or active) window is the one where we can draw to.We will store these dimensions in two global variables ScreenWidth% and ScreenHeight% using the following commands:ScreenWidth%=gWIDTHScreenHeight%=gHEIGHTPLANNING THE EVENT CORE, Init:45Because every Symbian OS phone has a slightly different way of presenting information, we need to realize where all the toolbars and widgetsare on screen, so we can calculate the size of the ‘empty’ window (or‘canvas’) we can use.Here are the variables being defined at the top of our code:GLOBAL ScreenMenubarOffset%, ScreenMainViewWindowOffset%GLOBAL ScreenStatusBarHeight%, ScreenLeftOffset%GLOBAL ScreenRightOffset%, Platform%And here is the code to calculate the size of the empty main window.We’re also using the variable Platform% so we can reference whatplatform we are running on – this information may be needed at anotherpoint in the program.IF 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%=0ENDIFThe values taken by Platform% are constants, which are variables wepre-define at the start of our program to make our code easier to read.

Tomake sure this technique works, add the following to the very top of yourOPL source code file:46EVENT CORECONSTCONSTCONSTCONSTKPlatformGeneric%=0KPlatformSeries80%=1KPlatformSeries60%=2KPlatformUIQ%=3We can now calculate our canvas size (i.e. the area we can actually drawto) for this phone:CanvasWidth%=ScreenWidth%-ScreenLeftOffset%-ScreenRightOffset%CanvasHeight%=ScreenHeight%-ScreenMainViewWindowOffset%ScreenStatusBarHeight%Set up Windows and Load GraphicsThere are two types of windows. The first are ones we can display onthe screen; these are called drawables.

The second are graphics you loadinto memory from a file; these are called bitmaps. When you create awindow, it is assigned a number, and this number is used throughout therest of the program to refer to it.These numbers are held in a GLOBAL array we create called Id%().So this is another variable we will need to define at the start of ourcode – as you sketch out your program you should keep a note of allthese variables, as it will make it easier when you come to write yourown source code.The gCREATE command creates a window that is displayed on thescreen. It looks like this:gCREATE(X%, Y%, Width%, Height%, ColorDepth%, Visibility%)X% and Y% represent the top left corner of the window we are creating.The very top left of the screen on your device is (0,0). You then specifythe width (Width%) and height (Height%) of the window.ColorDepth% is the number of colors that the window can show.The lower the number of colors, the less colors there are! There arevalues in Const.oph that relate to the value that needs to be used in theColorDepth% variable.Colours16256409665,53516 millionValueKdefaultWin16ColorMode%KdefaultWin256ColorMode%KDefaultWin4kMode%KdefaultWin64kMode%KDefaultWin16MMode%Finally, Visibility% is a binary value, where 1 means the windowcan be seen, and 0 means it is invisible, no matter what we draw in it.PLANNING THE EVENT CORE, Init:47In Event Core, we have one drawable, defined by this command:Id%(KMainViewWindow%)=gCREATE(ScreenLeftOffset%,ScreenMainViewWindowOffset%,(CanvasWidth%-ScreenLeftOffset%-ScreenRightOffset%),CanvasWidth%,CanvasHeight%,KDefaultWin4kMode%,1)Now this may look unnecessarily long, but do you remember wherewe calculated various screen sizes depending on what machine we areusing? This uses those numbers so that the same line of code will makesense no matter what platform you run Event Core on.We’ll look at bitmaps and graphics handling in more detail inChapter 5, so just be aware that this line loads a bitmap from a fileinto the memory:Id%(9)=gLOADBIT(Data$+MbmFiles$,0,0)Why 9 and not 2? Well, it’s up to you, but when I write code, I assignId%(1) to Id%(8) as drawables, and Id%(9) and greater as bitmaps.Directly after the gLOADBIT command we have three elements.

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

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

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

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