Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 71

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 71 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 712018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

You can tell what the 20bits are by looking at the RSG file. Here, for example, is OandX.rsg,which has the name OANX:#define#define#define#defineR_DEFAULT_DOCUMENT_NAMER_OANDX_MENUBARR_OANDX_MENUR_OANDX_O_WINS0x485b80020x485b80040x485b80050x485b8006COMPILING A RESOURCE FILE#define#define#define#defineR_OANDX_X_WINSR_OANDX_WHO_STARTSR_OANDX_O_MOVES_FIRSTR_OANDX_X_MOVES_FIRST3830x485b80070x485b80080x485b80090x485b800aUikon’s resource file name is EIK, and its resource IDs begin with0x00f3b.You don’t have to choose a name that’s distinct from all other SymbianOS applications on your system – with only four letters, that could betricky. The resource files available to your application are likely to beonly those from Uikon, Qikon or Avkon and your application, so yousimply have to avoid names starting with EIK, Q (for UIQ) and AKN (forS60).

Avoid CONE, BAFL, and other Symbian component names as well,and you should be safe.13.8 Compiling a Resource FileThe resource compiler is invoked as part of the application build process,either from within the IDE, or from the command line with, for example:abld build winscw udebAs we saw in Chapter 1, this command runs the build in six stages,one of which is resource compilation.From the command line, you can invoke the resource compiler alonewith a command of the form:abld resource winscw udebbut you must first have run the abld makefile command to ensure thatthe appropriate makefiles exist (type abld on its own to get help on theavailable options).Building for the winscw target by any of these methods causes the RSCfile to be generated in the \epoc32\release\winscw\<variant>\z\resource\apps directory (where <variant> is either udeb orurel).

Building for any ARM target causes the RSC file to be generatedin the \epoc32\data\z\resource\apps\ directory.To use a resource at run time, a program must specify the resourceID. The resource compiler therefore generates not only the resource file,but also a header file, with a .rsg extension, containing symbolic IDsfor every resource contained in the file. This header file is written tothe \epoc32\include\ directory, and is included in the application’ssource code. That’s why the resource compiler is run before you runthe C++ compiler when building a Symbian OS program.

The RSG fileis always generated to \epoc32\include\, but if the generated file384RESOURCE FILESis identical to one already in \epoc32\include\, the existing oneisn’t updated.Uikon has a vast treasury of specific resources (especially stringresources) accessible via the resource IDs listed in eikon.rsg.Figure 13.4 shows the overall build process, indicating the relationshipbetween the various file types involved..rh.loc.rls.rss.hrhResourcecompiler.rscC++build.app.rsg.cpp.hFigure 13.4 Build processApplication-specific input files to the resource compilation process fora typical application include those listed in Table 13.4.You may also need to include system RH files, such as eikon.rh,and other UI-specific RH files.In addition to AppName.hrh and the generated AppName.rsg file,C++ files might need to include system files such as eikon.rsg andeikon.hrh, together with one or more UI-specific RSG and HRH files.Conservative RSG UpdateWhen you compile OandX.rss, either from the CodeWarrior IDE or fromthe command line, it generates both the binary resource file OandX.rscand the generated header file OandX.rsg.The project correctly includes, for example, a dependency ofOandX.obj on OandX.rsg (because OandXAppUI.cpp includesOandX.rsg).

So, if OandX.rsg is updated, the OandX.exe projectneeds rebuilding. Scale this up to a large application, and a change inone resource file, and hence in the generated headers, could cause lotsof rebuilding.The resource compiler avoids this potential problem by updating theRSG file only when necessary – and it isn’t necessary unless resource IDshave changed. Merely changing the text of a string or the placement of aGUI element won’t cause the application’s executable to go out of date.This is why, when you run the resource compiler, you are notified ifthe RSG file has been changed.THE CONTENT OF A COMPILED RESOURCE FILE385Table 13.4 Application-specific Input filesFilenameDescriptionAppName.rssThe application’s resource script.AppName reg.rssThe application’s registration file.AppName.rls orAppName.locThe application’s localizable strings.AppName.rscThe generated resource file.AppName.rsgGenerated header containing symbolic resource IDsthat are included in the C++ program at build time.AppName.hrhAn application-specific header containing symbolicconstants, for example the command IDs which areembedded into resources such as the menus, buttonbars and, if relevant, shortcut keys.

Such header filesare used by both resource scripts and C++ sourcefiles, in places such as HandleCommandL().AppName.locThe application’s localizable strings.Eikon.rhHeader files that define Uikon’s standard STRUCTsfor resources.Eikon.hrhHeader files that define Uikon’s standard symbolicIDs, such as the command ID for EEikCmdExit,and the flags used in various resource STRUCTs.Eikon.rsgResource IDs for Uikon’s own resource files, whichcontain many useful resources. Many of theseresources are for internal use by Symbian OS,although some are also available for applicationprograms to use.13.9 The Content of a Compiled Resource FileThe resource compiler builds the run-time resource file sequentially,starting with header information that identifies the file as being a resourcefile.

It then appends successive resources to the end of the file, in theorder of definition. The resource compiler will not have built a completeindex until the end of the source file is reached; hence the index is thelast thing to be built and appears at the end of the file.Each index entry is a word that contains the offset in bytes from thebeginning of the file to the start of the appropriate resource. The index386RESOURCE FILES123456Logical viewStart ofresource dataIndexpointerStart ofindexFile layoutFigure 13.5 Compiled resource file structurecontains, at the end, an additional entry that contains the offset to thebyte immediately following the last resource, which is also the start of theindex. The structure is illustrated in Figure 13.5.Each resource is simply binary data, whose length may be found bysubtracting its own index entry from that of the following resource.

Tosee what a compiled resource looks like, let’s take a look at a resourcefrom the Noughts and Crosses example.The menu pane and menu item resource STRUCTs are declared inuikon.rh as follows:STRUCT MENU_PANE{STRUCT items[]; // MENU_ITEMsLLINK extension=0;}STRUCT MENU_ITEM{LONG command=0;LLINK cascade=0;LONG flags=0;LTEXT txt;LTEXT extratxt="";LTEXT bmpfile="";THE CONTENT OF A COMPILED RESOURCE FILE387WORD bmpid=0xffff;WORD bmpmask=0xffff;LLINK extension=0;}and the menu pane resource itself is:RESOURCE MENU_PANE r_oandx_menu{items ={MENU_ITEM{command = EOandXNewGame;txt = "Item 0";},MENU_ITEM{command = EEikCmdExit;txt = "Close (debug)";}};}As you can see, each of the two menu items only specify two of thenine elements; the remaining seven take the default values as specified inthe declaration.If you were to analyze a hex dump of a resource file, you wouldclearly see the text of the various strings that are defined.

However,you might be slightly puzzled: we have said that Symbian OS applications use a Unicode build, whereas these strings appear to be plainASCII text. Furthermore, if you count through the resource, identifying items on the way, you will find that there is an occasional extrabyte here and there – for example, each of the strings appears to bepreceded by two identical count bytes, instead of the expected singlebyte.This occurs because the compiled resource is compressed, in orderto save space in Unicode string data.

The content of the resource isdivided into a sequence of runs, alternating between compressed anduncompressed data. Each run is preceded by a count of the characters inthat run, with the count being held in a single byte, provided that the runis no more than 255 bytes in length.Apart from the effects of data compression, the compiled resourcejust contains the individual elements, listed sequentially. A WORD, forexample, occupies two bytes, and an LTEXT is represented by a bytespecifying the length, followed by the text. Where there are embeddedSTRUCTs, the effect is to flatten the structure. The run-time interpretationof the data is the responsibility of the class or function that uses it.38813.10RESOURCE FILESReading Resource FilesVia CCoeEnvThe application framework opens the application’s resource file duringthe startup of the application.

The most straightforward way to readone of its resources is to call CCoeEnv’s AllocReadResourceL()or AllocReadResourceLC() functions, which take a resource IDas a parameter. Both functions allocate an HBufC big enough for theuncompressed resource and read it in. CCoeEnv also supplies variantsof these two functions to read a resource as explicit 8-bit or 16-bitdescriptors, or descriptor arrays.text = iEikonEnv->AllocReadResourceL(R_MSG_1);Alternatively, you can use CCoeEnv’s ReadResource() function,which simply reads a resource into an existing descriptor, and panics ifthe read fails.TBuf<16> ECommandText;iEikonEnv->ReadResource(ECommandText, R_MSG_2);Via BAFLBAFL provides the basic APIs for reading resources:• the oddly-named RResourceFile class, declared in barsc.h, isused for opening resource files, finding a numbered resource, andreading its data.

(RResourceFile behaves more like a C class thanan R class.)• TResourceReader, declared in barsread.h, is a kind of streamoriented reader for data in an individual resource. TResourceReaderfunctions are provided that correspond to each of the resource compiler’s built-in data types.As an example of the use of TResourceReader functions, here’s thecode to read in a MENU_ITEM resource:EXPORT_C void CEikMenuPaneItem::ConstructFromResourceL(TResourceReader& aReader){iData.iCommandId=aReader.ReadInt32();iData.iCascadeId=aReader.ReadInt32();iData.iFlags=aReader.ReadInt32();iData.iText=aReader.ReadTPtrC();SUMMARY389iData.iExtraText=aReader.ReadTPtrC();TPtrC bitmapFile=aReader.ReadTPtrC();TInt bitmapId=aReader.ReadInt16();TInt maskId=aReader.ReadInt16();aReader.ReadInt32(); // extension linkif (bitmapId != -1){SetIcon(CEikonEnv::Static()->CreateIconL(bitmapFile, bitmapId,maskId));}}In this code, a TResourceReader pointing to the correct (uncompressed) resource has already been created by the framework, so all thiscode has to do is actually read the resource.The code exactly mirrors the resource STRUCT definition:the MENU_ITEM definition starts with LONG command, so the resourcereading code starts with:iData.iCommandId=aReader.ReadInt32()The next defined item is LLINK cascade, which is read byiData.iCascadeId=aReader.ReadInt32()and so on.All resource reading functions will uncompress any compressed data.SummaryIn this chapter, we’ve seen:• why a Symbian OS-specific resource compiler is needed• a brief explanation of the syntax• using bitmaps for the application icon• the new registration files required by Symbian OS v9• how to organize your resource text to ease the task of localization• how to use multiple resource files• how to read data from a resource file.14Views and the View ArchitectureIn general terms, a view can be defined as any class that enables you todisplay some or all of an application’s data.

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

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

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

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