Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 94

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 94 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 942018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

This type of anim DLL is now called a ‘‘windowanim’’, and to create one you would return an object derived fromCWindowAnim from CreateInstanceL().To provide digital ink on-screen, we developed a new type of animthat allowed drawing to a sprite.

This is known as a ‘‘sprite anim’’, and444THE WINDOW SERVERto create one you would return an object derived from CSpriteAnimfrom CreateInstanceL(). The relationships between these, and other,classes are shown in Figure 11.2.MEventHandlerCBaseCGraphicsContextOfferRawEvent()CBitmapContextCAnimiFunctionsAnimate()Command()CommandReplyL()CSpriteAnimiSpriteFunctionsCAnimGcCWindowAnimiWindowFunctionsFocusChanged()Redraw()Figure 11.2 Animation class hierarchyThere are two types of functions in the anim interface.

Firstly, there arefunctions in the anim that WSERV calls. These are shown in the diagramas member functions of the four classes: MEventHandler, CAnim,CSpriteAnim and CWindowAnim; they are all pure virtual functionsand so the anim writer has to provide implementations for the relevantset of these functions, depending on which class she has derived from.The WSERV functions that an anim can call are provided by means ofthe member data shown in Figure 11.2.

There are four in all, shown withthe class they belong to in parentheses:• iFunctions (MAnimGeneralFunctions)• iSpriteFunctions (MAnimSpriteFunctions)• iWindowFunctions (MAnimWindowFunctions)• iGc (CAnimGc).CAnimGc provides drawing functions that the window anim uses to drawto its window.Thus our example CHandWritingAnim is a sub-class of CSpriteAnim.A SIMPLE HANDWRITING ANIMATION DLL44511.7.3 Functions a sprite anim must provideAll the derived classes of CSpriteAnim must provide all the virtualfunctions of that class, CAnim and MEventHandler, so part of our classdefinition will be:class CHandWritingAnim : public CSpriteAnim{public:∼CHandWritingAnim();//pure virtual functions from CSpriteAnimvoid ConstructL(TAny* aArgs);//pure virtual functions from MEventHandlerTBool OfferRawEvent(const TRawEvent& aRawEvent);//pure virtual functions from CAnimvoid Animate(TdateTime* aDateTime);void Command(TInt aOpcode,TAny* aArgs);TInt CommandReplyL(TInt aOpcode,TAny* aArgs);private:TInt iState;CFbsBitmapDevice* iBitmapDevice;CFbsBitmapDevice* iMaskBitmapDevice;CFbsBitGc* iSpriteGc;TBool iIsMask;CPointStore* iPointStore;};I will talk about the purpose of these functions in the followingsections.11.7.3.1 ConstructionThe first anim DLL function that will be called is CSpriteAnim::ConstructL.

WSERV calls this function when responding to the client’scall to RAnim::Construct(). The parameter aArgs passed to theConstructL function is a pointer to a copy of the content of thedescriptor that was originally passed in to the client-side Constructfunction. It will normally need casting to the correct type.void CHandWritingAnim::ConstructL(TAny* ){TSpriteMember* spriteMember=iSpriteFunctions->GetSpriteMember(0);iIsMask=(spriteMember->iBitmap->Handle()!=spriteMember->iMaskBitmap->Handle());iBitmapDevice=CFbsBitmapDevice::NewL(spriteMember->iBitmap);if (iIsMask)iMaskBitmapDevice=CFbsBitmapDevice::NewL(spriteMember->iMaskBitmap);iSpriteGc=CFbsBitGc::NewL();iSpriteGc->Reset();iState=EHwStateInactive;446THE WINDOW SERVERiPointStore=new(ELeave) CPointStore();iPointStore->ConstructL();iSpriteFunctions->SizeChangedL();...}The call to GetSpriteMember() returns details of the sprite that thisanim is allowed to draw to.

Usually, sprites can animate. To do this, aclient needs to give a sprite several members – each member containsone frame of the animation. In this case, the client only needs to createone frame for the ink and thus we specify a value of ‘‘0’’ as the parameterin this function call. This is then checked to see if the client has providedseparate bitmaps for the mask and the sprite content.

Drawing to anygraphics object, such as a bitmap or the screen, requires a device forthat object. From a device, we can create a graphics context (or GC)and use this to do the drawing. We now create the following objects – aCFbsBitmapDevice for each bitmap and a single CFbsBitGc whichcan be used on both bitmaps.The state member, iState, is initialized to say that no handwritingrecognition is currently required. Since the shape drawn on the screen isto be converted to a character, we create a point store so that the detailedshape of the ink can be recorded. The call to SizeChangedL() is partof the standard, general initialization of a sprite.

It sets up the backupbitmap for the sprite, which needs to be the size of the largest frame. Thisfunction will go on to set the parameters for the ink, such as color andline width – this is not shown in the previous code segment.11.7.3.2 Receiving eventsEvents are received when WSERV calls the function: MEventHandler::OfferRawEvent(), see Section 11.3, How WSERV processesevents. Remember that this function was pure virtual in the base class,and so I have an implementation in my CHandwritingAnim class. Bydefault, WSERV will not pass events to anims, so if the anim wants toreceive the events, it has to call the function MAnimGeneralFunctions::GetRawEvents(), passing in the parameter ETrue.

Once anevent has been passed to the Anim DLL, it has to return a TBool to say ifit has consumed the event (ETrue) or not (EFalse):TBool CHandWritingAnim::OfferRawEvent(const TRawEvent &aRawEvent){if (iState==EHwStateDeactive)return EFalse;switch (aRawEvent.Type()){case TRawEvent::EButton1Down:A SIMPLE HANDWRITING ANIMATION DLL447return HandlePointerDown(aRawEvent.Pos());case TRawEvent::EPointerMove:return HandlePointerMove(aRawEvent.Pos());case TRawEvent::EButton1Up:return HandlePointerUp(aRawEvent.Pos());default:return EFalse;}}The first thing this function does is to check to see if handwriting isturned on.

If it is not, it will return EFalse to tell WSERV to processthe event itself. It also does this if the event is not a pointer event; thisis what the default part of the switch statement is for. This functionthen calls three other functions that will process the pointer events. Ihave not shown an implementation of these functions, but will note thatit would be advisable for them to adopt the strategy that if the userclicks and holds for a certain length of time, then this should be treatedas a pointer to be sent to applications, rather than for drawing digitalink.11.7.3.3 AnimatingThe Animate() function is designed for receiving periodic events toupdate the clock.void Animate(TDateTime* aDateTime);By default, WSERV does not call this virtual function.

If an anim doeswant it to be called, then the anim should call this function:void MAnimGeneralFunctions::SetSync(TAnimSync aSyncMode);The parameter specifies how often to call the Animate() function. Theoptions are:enum TAnimSync{ESyncNone,ESyncFlash,ESyncSecond,ESyncMinute,ESyncDay,};Clearly ESyncNone means that WSERV never animates. The remainingthree values tell WSERV to call the animate function after the specifiedtime intervals.448THE WINDOW SERVERThe second value is slightly different.

It tells WSERV to animate twicea second. However, these animations are not evenly spaced, every halfa second – they happen on the second and after 7/12 of a second. Thisis so that when the separator character (the ‘‘:’’ in ‘‘12:45:37’’) flashesit will be visible for slightly longer than it is invisible. (WSERV uses thesame internal timer to flash the cursor (and sprites), which also are visiblefor slightly longer than they are invisible.)To do these animations, WSERV uses a lock timer (possibly the onlyuse of a lock timer in Symbian OS).

This timer makes it easy for WSERVto determine if the system is running slowly. Its API is:void CTimer::Lock(TTimerLockSpec aLock);The parameter specifies a particular twelfth of a second. The first timethe function is called, the kernel will signal the associated active objectwhen it reaches that point in the second.

The second time the functionis called, the kernel will only signal the active object if the requestedtwelfth of the second is within a second of the first requested point. If itis not, the function will return with an error, showing that the system isvery busy.Suppose, for example, that a clock uses this timer to update a display ofseconds. Each second, the clock calls the lock timer to ask to be notifiedwhen the current second is over. At the next second boundary, the kernelsignals the active object. If the active object runs and re-queues itselfwithin that second, everything is fine. If the system is busy and by thetime the active object runs and re-queues itself, the second had passed,then the active object will complete with an error telling the clock that itneeds to reset itself, rather than just doing an increment.When WSERV gets an error back from the lock timer, it tells theanim that it should reset itself by passing the current date-time to theanimate function.

(When things are running normally, it passes NULL tothis function.)Although the handwriting anim does not need to do any animation,it does need a timer. Instead of creating its own timer, it uses theCTimer::Lock() function to receive timer notifications – I will saymore on this later.11.7.3.4 Client communicationThe following functions can both receive commands from the client side:TInt CAnim::CommandReplyL(TInt aOpcode, TAny* aArgs)=0;void CAnim::Command(TInt aOpcode, TAny* aArgs)=0;One difference between them is that the first one can also return a TIntvalue to the client. It can do this either by returning the value to send backA SIMPLE HANDWRITING ANIMATION DLL449to the client, or by leaving – the leave code will then be sent to the client.Another difference between these two functions is that the first one is sentdirectly to the window server.

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

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

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

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