code:
/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SkWidgetViews_DEFINED
#define SkWidgetViews_DEFINED

#include "SkView.h"

enum SkWidgetEnum {
    kBorder_WidgetEnum,         //!< <sk-border>
    kButton_WidgetEnum,         //!< <sk-button>
    kImage_WidgetEnum,          //!< <sk-image>
    kList_WidgetEnum,           //!< <sk-list>
    kProgress_WidgetEnum,       //!< <sk-progress>
    kScroll_WidgetEnum,         //!< <sk-scroll>
    kText_WidgetEnum,           //!< <sk-text>

    kWidgetEnumCount
};

//determines which skin to use
enum SkinEnum {
    kBorder_SkinEnum,
    kButton_SkinEnum,
    kProgress_SkinEnum,
    kScroll_SkinEnum,
    kStaticText_SkinEnum,

    kSkinEnumCount
};

#include "SkAnimator.h"
//used for inflates
const char* get_skin_enum_path(SkinEnum se);
void init_skin_anim(const char path[], SkAnimator* anim);
void init_skin_anim(SkinEnum se, SkAnimator* anim);
void init_skin_paint(SkinEnum se, SkPaint* paint);
void inflate_paint(const SkDOM& dom, const SkDOM::Node* node, SkPaint* paint);

/** Given an enum value, return an instance of the specified widget.
    If the enum is out of range, returns null
*/
SkView* SkWidgetFactory(SkWidgetEnum);
/** Given the inflate/element name of a widget, return an instance of
    the specified widget, or null if name does not match any known
    widget type.
*/
SkView* SkWidgetFactory(const char name[]);

////////////////////////////////////////////////////////////////////////////////////////////////

class SkWidgetView : public SkView {
public:
    SkWidgetView();

    const char* getLabel() const;
    void        getLabel(SkString* label) const;

    void        setLabel(const char[]);
    void        setLabel(const char[], size_t len);
    void        setLabel(const SkString&);

    SkEvent&        event() { return fEvent; }
    const SkEvent&  event() const { return fEvent; }

    /** Returns true if the widget can post its event to its listeners.
    */
    bool    postWidgetEvent();

    /** Returns the sinkID of the widgetview that posted the event, or 0
    */
    static SkEventSinkID GetWidgetEventSinkID(const SkEvent&);

protected:
    /** called when the label changes. override in subclasses. default action invals the view's bounds.
        called with the old and new labels, before the label has actually changed.
    */
    virtual void onLabelChange(const char oldLabel[], const char newLabel[]);
    /** called before posting the event to our listeners. Override to add slots to the event
        before posting. Return true to proceed with posting, or false to not post the event to any
        listener. Note: the event passed in may not be the same as calling this->event().
        Be sure to call your INHERITED method as well, so that all classes in the hierarchy get a shot
        at modifying the event (and possibly returning false to abort).
    */
    virtual bool onPrepareWidgetEvent(SkEvent* evt);

    // overrides
    virtual void onInflate(const SkDOM& dom, const SkDOM::Node*);

private:
    SkString    fLabel;
    SkEvent     fEvent;

    typedef SkView INHERITED;
};

////////////////////////////////////////////////////////////////////////////////////////////////

class SkButtonView : public SkWidgetView {
public:
    // inflate: "sk-button"

protected:
    // overrides
    virtual bool onEvent(const SkEvent&);
private:
    typedef SkWidgetView INHERITED;
};

////////////////////////////////////////////////////////////////////////////////////////////////

class SkCheckButtonView : public SkWidgetView {
public:
    SkCheckButtonView();

    // inflate: "sk-checkbutton"

    enum CheckState {
        kOff_CheckState,        //!< inflate: check-state="off"
        kOn_CheckState,         //!< inflate: check-state="on"
        kUnknown_CheckState     //!< inflate: check-state="unknown"
    };
    CheckState  getCheckState() const { return (CheckState)fCheckState; }
    void        setCheckState(CheckState);

    /** use this to extract the CheckState from an event (i.e. one that as posted
        by a SkCheckButtonView). Returns true if the proper slot was present in the event,
        and sets state to that value. If no proper slot is found, returns false and does not
        modify state.
    */
    static bool GetWidgetEventCheckState(const SkEvent&, CheckState* state);

protected:
    // called when the check-state is about to change, but before it actually has
    virtual void onCheckStateChange(CheckState oldState, CheckState newState);

    // overrides
    virtual void onInflate(const SkDOM& dom, const SkDOM::Node*);
    virtual bool onPrepareWidgetEvent(SkEvent* evt);

private:
    uint8_t  fCheckState;

    typedef SkWidgetView INHERITED;
};

////////////////////////////////////////////////////////////////////////////////////////////////
#include "SkTextBox.h"

class SkStaticTextView : public SkView {
public:
            SkStaticTextView();
    virtual ~SkStaticTextView();

    enum Mode {
        kFixedSize_Mode,
        kAutoWidth_Mode,
        kAutoHeight_Mode,

        kModeCount
    };
    Mode    getMode() const { return (Mode)fMode; }
    void    setMode(Mode);

    SkTextBox::SpacingAlign getSpacingAlign() const { return (SkTextBox::SpacingAlign)fSpacingAlign; }
    void    setSpacingAlign(SkTextBox::SpacingAlign);

    void    getMargin(SkPoint* margin) const;
    void    setMargin(SkScalar dx, SkScalar dy);

    size_t  getText(SkString* text = NULL) const;
    size_t  getText(char text[] = NULL) const;
    void    setText(const SkString&);
    void    setText(const char text[]);
    void    setText(const char text[], size_t len);

    void    getPaint(SkPaint*) const;
    void    setPaint(const SkPaint&);

protected:
    // overrides
    virtual void onDraw(SkCanvas*);
    virtual void onInflate(const SkDOM& dom, const SkDOM::Node*);

private:
    SkPoint     fMargin;
    SkString    fText;
    SkPaint     fPaint;
    uint8_t     fMode;
    uint8_t     fSpacingAlign;

    void computeSize();

    typedef SkView INHERITED;
};

////////////////////////////////////////////////////////////////////////////////////////////////

class SkAnimator;
class SkListSource;
class SkScrollBarView;

class SkListView : public SkWidgetView {
public:
            SkListView();
    virtual ~SkListView();

    bool    hasScrollBar() const { return fScrollBar != NULL; }
    void    setHasScrollBar(bool);

    /** Return the number of visible rows
    */
    int     getVisibleRowCount() const { return fVisibleRowCount; }
    /** Return the index of the selected row, or -1 if none
    */
    int     getSelection() const { return fCurrIndex; }
    /** Set the index of the selected row, or -1 for none
    */
    void    setSelection(int);
    /** If possible, move the selection up and return true,
        else do nothing and return false
        If nothing is selected, select the last item (unless there are no items).
    */
    bool    moveSelectionUp();
    /** If possible, move the selection down and return true,
        else do nothing and return false.
        If nothing is selected, select the first item (unless there are no items).
    */
    bool    moveSelectionDown();

    SkListSource*   getListSource() const { return fSource; }
    SkListSource*   setListSource(SkListSource*);

    /** Call this in your event handler. If the specified event is from a SkListView,
        then it returns the index of the selected item in this list, otherwise it
        returns -1
    */
    static int GetWidgetEventListIndex(const SkEvent&);

protected:
    // overrides
    virtual void onDraw(SkCanvas*);
    virtual void onSizeChange();
    virtual bool onEvent(const SkEvent&);
    virtual void onInflate(const SkDOM& dom, const SkDOM::Node* node);
    virtual bool onPrepareWidgetEvent(SkEvent*);

private:
    enum DirtyFlags {
        kAnimCount_DirtyFlag    = 0x01,
        kAnimContent_DirtyFlag  = 0x02
    };
    void    dirtyCache(unsigned dirtyFlags);
    bool    ensureCache();

    int     logicalToVisualIndex(int index) const { return index - fScrollIndex; }
    void    invalSelection();
    SkScalar getContentWidth() const;
    bool    getRowRect(int index, SkRect*) const;
    void    ensureSelectionIsVisible();
    void    ensureVisibleRowCount();

    struct BindingRec;

    enum Heights {
        kNormal_Height,
        kSelected_Height
    };
    SkListSource*   fSource;
    SkScrollBarView*    fScrollBar;
    SkAnimator*     fAnims;
    BindingRec*     fBindings;
    SkString        fSkinName;
    SkScalar        fHeights[2];
    int16_t         fScrollIndex, fCurrIndex;
    uint16_t        fVisibleRowCount, fBindingCount;
    SkBool8         fAnimContentDirty;
    SkBool8         fAnimFocusDirty;

    typedef SkWidgetView INHERITED;
};

class SkListSource : public SkRefCnt {
public:
    virtual int countFields();
    virtual void getFieldName(int index, SkString* field);
    /** Return the index of the named field, or -1 if not found */
    virtual int findFieldIndex(const char field[]);

    virtual int countRecords();
    virtual void getRecord(int rowIndex, int fieldIndex, SkString* data);

    virtual bool prepareWidgetEvent(SkEvent*, int rowIndex);

    static SkListSource* Factory(const char name[]);
};

#endif


code:
/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SkWindow_DEFINED
#define SkWindow_DEFINED

#include "SkView.h"
#include "SkBitmap.h"
#include "SkMatrix.h"
#include "SkRegion.h"
#include "SkEvent.h"
#include "SkKey.h"
#include "SkTDArray.h"

#ifdef SK_BUILD_FOR_WINCEx
    #define SHOW_FPS
#endif
//#define USE_GX_SCREEN

class SkCanvas;

class SkOSMenu;

class SkWindow : public SkView {
public:
            SkWindow();
    virtual ~SkWindow();

    const SkBitmap& getBitmap() const { return fBitmap; }

    void    setConfig(SkBitmap::Config);
    void    resize(int width, int height, SkBitmap::Config config = SkBitmap::kNo_Config);
    void    eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
    void    eraseRGB(U8CPU r, U8CPU g, U8CPU b);

    bool    isDirty() const { return !fDirtyRgn.isEmpty(); }
    bool    update(SkIRect* updateArea, SkCanvas* = NULL);
    // does not call through to onHandleInval(), but does force the fDirtyRgn
    // to be wide open. Call before update() to ensure we redraw everything.
    void    forceInvalAll();
    // return the bounds of the dirty/inval rgn, or [0,0,0,0] if none
    const SkIRect& getDirtyBounds() const { return fDirtyRgn.getBounds(); }

    bool    handleClick(int x, int y, Click::State, void* owner = NULL);
    bool    handleChar(SkUnichar);
    bool    handleKey(SkKey);
    bool    handleKeyUp(SkKey);
    bool    handleMenu(uint32_t os_cmd);

    void    addMenu(SkOSMenu*);

    const char* getTitle() const { return fTitle.c_str(); }
    void    setTitle(const char title[]);

    const SkMatrix& getMatrix() const { return fMatrix; }
    void    setMatrix(const SkMatrix&);
    void    preConcat(const SkMatrix&);
    void    postConcat(const SkMatrix&);

    virtual void onPDFSaved(const char title[], const char desc[],
        const char path[]) {}
protected:
    virtual bool onEvent(const SkEvent&);
    virtual bool onDispatchClick(int x, int y, Click::State, void* owner);
    // called if part of our bitmap is invalidated
    virtual void onHandleInval(const SkIRect&);
    virtual bool onHandleChar(SkUnichar);
    virtual bool onHandleKey(SkKey);
    virtual bool onHandleKeyUp(SkKey);
    virtual void onAddMenu(const SkOSMenu*) {}
    virtual void onSetTitle(const char title[]) {}

    // overrides from SkView
    virtual bool handleInval(const SkRect*);
    virtual bool onGetFocusView(SkView** focus) const;
    virtual bool onSetFocusView(SkView* focus);

private:
    SkBitmap::Config    fConfig;
    SkBitmap    fBitmap;
    SkRegion    fDirtyRgn;

    SkTDArray<Click*>       fClicks; // to track clicks

    SkTDArray<SkOSMenu*>    fMenus;

    SkView* fFocusView;
    bool    fWaitingOnInval;

    SkString    fTitle;
    SkMatrix    fMatrix;

    typedef SkView INHERITED;
};

///////////////////////////////////////////////////////////

#ifdef SK_USE_WXWIDGETS
    #include "SkOSWindow_wxwidgets.h"
#elif defined(SK_BUILD_FOR_MAC)
    #include "SkOSWindow_Mac.h"
#elif defined(SK_BUILD_FOR_WIN)
    #include "SkOSWindow_Win.h"
#elif defined(ANDROID)
    #include "SkOSWindow_Android.h"
#elif defined(SK_BUILD_FOR_UNIX)
  #include "SkOSWindow_Unix.h"
#elif defined(SK_BUILD_FOR_SDL)
    #include "SkOSWindow_SDL.h"
#elif defined(SK_BUILD_FOR_IOS)
    #include "SkOSWindow_iOS.h"
#endif

#endif

license: mit


code:
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SkWriter32_DEFINED
#define SkWriter32_DEFINED

#include "SkTypes.h"

#include "SkScalar.h"
#include "SkPoint.h"
#include "SkRect.h"

class SkStream;
class SkWStream;

class SkWriter32 : SkNoncopyable {
public:
    SkWriter32(size_t minSize)
        : fMinSize(minSize),
          fSize(0),
          fSingleBlock(NULL),
          fSingleBlockSize(0),
          fHead(NULL),
          fTail(NULL) {
    }
    ~SkWriter32();

    /**
     *  Returns the single block backing the writer, or NULL if the memory is
     *  to be dynamically allocated.
     */
    void* getSingleBlock() const { return fSingleBlock; }

    /**
     *  Specify the single block to back the writer, rathern than dynamically
     *  allocating the memory. If block == NULL, then the writer reverts to
     *  dynamic allocation (and resets).
     */
    void reset(void* block, size_t size);

    bool writeBool(bool value) {
        this->writeInt(value);
        return value;
    }

    void writeInt(int32_t value) {
        *(int32_t*)this->reserve(sizeof(value)) = value;
    }

    void write8(int32_t value) {
        *(int32_t*)this->reserve(sizeof(value)) = value & 0xFF;
    }

    void write16(int32_t value) {
        *(int32_t*)this->reserve(sizeof(value)) = value & 0xFFFF;
    }

    void write32(int32_t value) {
        *(int32_t*)this->reserve(sizeof(value)) = value;
    }

    void writeScalar(SkScalar value) {
        *(SkScalar*)this->reserve(sizeof(value)) = value;
    }

    void writePoint(const SkPoint& pt) {
        *(SkPoint*)this->reserve(sizeof(pt)) = pt;
    }

    void writeRect(const SkRect& rect) {
        *(SkRect*)this->reserve(sizeof(rect)) = rect;
    }

    // write count bytes (must be a multiple of 4)
    void writeMul4(const void* values, size_t size) {
        this->write(values, size);
    }

    /**
     *  Write size bytes from values. size must be a multiple of 4, though
     *  values need not be 4-byte aligned.
     */
    void write(const void* values, size_t size) {
        SkASSERT(SkAlign4(size) == size);
        // if we could query how much is avail in the current block, we might
        // copy that much, and then alloc the rest. That would reduce the waste
        // in the current block
        memcpy(this->reserve(size), values, size);
    }

    void writePad(const void* src, size_t size);

    /**
     *  Writes a string to the writer, which can be retrieved with
     *  SkReader32::readString().
     *  The length can be specified, or if -1 is passed, it will be computed by
     *  calling strlen(). The length must be < 0xFFFF
     */
    void writeString(const char* str, size_t len = (size_t)-1);

    /**
     *  Computes the size (aligned to multiple of 4) need to write the string
     *  in a call to writeString(). If the length is not specified, it will be
     *  computed by calling strlen().
     */
    static size_t WriteStringSize(const char* str, size_t len = (size_t)-1);

    // return the current offset (will always be a multiple of 4)
    uint32_t  size() const { return fSize; }
    void      reset();
    uint32_t* reserve(size_t size); // size MUST be multiple of 4

    // return the address of the 4byte int at the specified offset (which must
    // be a multiple of 4. This does not allocate any new space, so the returned
    // address is only valid for 1 int.
    uint32_t* peek32(size_t offset);

    // copy into a single buffer (allocated by caller). Must be at least size()
    void flatten(void* dst) const;

    // read from the stream, and write up to length bytes. Return the actual
    // number of bytes written.
    size_t readFromStream(SkStream*, size_t length);

    bool writeToStream(SkWStream*);

private:
    size_t      fMinSize;
    uint32_t    fSize;

    char*       fSingleBlock;
    uint32_t    fSingleBlockSize;

    struct Block;
    Block*  fHead;
    Block*  fTail;

    Block* newBlock(size_t bytes);
};

#endif


code:
/* libs/graphics/animator/SkXMLAnimatorWriter.h
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/

#ifndef SkXMLAnimatorWriter_DEFINED
#define SkXMLAnimatorWriter_DEFINED

#include "SkXMLWriter.h"

class SkAnimator;
class SkDisplayXMLParser;

class SkXMLAnimatorWriter : public SkXMLWriter {
public:
    SkXMLAnimatorWriter(SkAnimator*);
    virtual ~SkXMLAnimatorWriter();
    virtual void    writeHeader();
    SkDEBUGCODE(static void UnitTest(class SkCanvas* canvas);)
protected:
    virtual void onAddAttributeLen(const char name[], const char value[], size_t length);
    virtual void onEndElement();
    virtual void onStartElementLen(const char elem[], size_t length);
private:
    SkAnimator* fAnimator;
    SkDisplayXMLParser* fParser;
};

#endif // SkXMLAnimatorWriter_DEFINED


code:
/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SkXMLParser_DEFINED
#define SkXMLParser_DEFINED

#include "SkMath.h"
#include "SkString.h"

class SkStream;

class SkDOM;
struct SkDOMNode;

class SkXMLParserError {
public:
    enum ErrorCode {
        kNoError,
        kEmptyFile,
        kUnknownElement,
        kUnknownAttributeName,
        kErrorInAttributeValue,
        kDuplicateIDs,
        kUnknownError
    };

    SkXMLParserError();
    virtual ~SkXMLParserError();
    ErrorCode getErrorCode() const { return fCode; }
    virtual void getErrorString(SkString* str) const;
    int getLineNumber() const { return fLineNumber; }
    int getNativeCode() const { return fNativeCode; }
    bool hasError() const { return fCode != kNoError || fNativeCode != -1; }
    bool hasNoun() const { return fNoun.size() > 0; }
    void reset();
    void setCode(ErrorCode code) { fCode = code; }
    void setNoun(const SkString& str) { fNoun.set(str); }
    void setNoun(const char* ch)  { fNoun.set(ch); }
    void setNoun(const char* ch, size_t len) { fNoun.set(ch, len); }
protected:
    ErrorCode fCode;
private:
    int fLineNumber;
    int fNativeCode;
    SkString fNoun;
    friend class SkXMLParser;
};

class SkXMLParser {
public:
            SkXMLParser(SkXMLParserError* parserError = NULL);
    virtual ~SkXMLParser();

    /** Returns true for success
    */
    bool parse(const char doc[], size_t len);
    bool parse(SkStream& docStream);
    bool parse(const SkDOM&, const SkDOMNode*);

    static void GetNativeErrorString(int nativeErrorCode, SkString* str);

protected:
    // override in subclasses; return true to stop parsing
    virtual bool onStartElement(const char elem[]);
    virtual bool onAddAttribute(const char name[], const char value[]);
    virtual bool onEndElement(const char elem[]);
    virtual bool onText(const char text[], int len);

public:
    // public for ported implementation, not meant for clients to call
    virtual bool startElement(const char elem[]);
    virtual bool addAttribute(const char name[], const char value[]);
    virtual bool endElement(const char elem[]);
    virtual bool text(const char text[], int len);
    void* fParser;
protected:
    SkXMLParserError* fError;
private:
    void reportError(void* parser);
};

#if 0
class SkXMLPullParser {
public:
            SkXMLPullParser();
    explicit SkXMLPullParser(SkStream*);
    virtual ~SkXMLPullParser();

    SkStream*   getStream() const { return fStream; }
    SkStream*   setStream(SkStream* stream);

    enum EventType {
        ERROR = -1,
        START_DOCUMENT,
        END_DOCUMENT,
        START_TAG,
        END_TAG,
        TEXT,
        CDSECT,
        ENTITY_REF,
        IGNORABLE_WHITESPACE,
        PROCESSING_INSTRUCTION,
        COMMENT,
        DOCDECL
    };

    EventType   nextToken();
    EventType   getEventType() const { return fCurr.fEventType; }

    struct AttrInfo {
        const char* fName;
        const char* fValue;
    };

    int         getDepth() const { return fDepth; }
    const char* getName();
    int         getAttributeCount();
    void        getAttributeInfo(int, AttrInfo*);
    const char* getText();
    bool        isWhitespace();

protected:
    virtual bool onEntityReplacement(const char name[],
                                     SkString* replacement);

public:
    struct Curr {
        EventType   fEventType;
        const char* fName;
        AttrInfo*   fAttrInfos;
        int         fAttrInfoCount;
        bool        fIsWhitespace;
    };

private:
    // implemented in the porting layer
    bool        onInit();   // return false on failure
    EventType   onNextToken();
    void        onExit();

    SkStream*   fStream;
    Curr        fCurr;
    int         fDepth;

    struct Impl;
    Impl*   fImpl;
};
#endif

#endif


code:
/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SkXMLWriter_DEFINED
#define SkXMLWriter_DEFINED

#include "SkTDArray.h"
#include "SkString.h"
#include "SkDOM.h"

class SkWStream;
class SkXMLParser;

class SkXMLWriter {
public:
            SkXMLWriter(bool doEscapeMarkup = true);
    virtual ~SkXMLWriter();

    void    addS32Attribute(const char name[], int32_t value);
    void    addAttribute(const char name[], const char value[]);
    void    addAttributeLen(const char name[], const char value[], size_t length);
    void    addHexAttribute(const char name[], uint32_t value, int minDigits = 0);
    void    addScalarAttribute(const char name[], SkScalar value);
    void    endElement() { this->onEndElement(); }
    void    startElement(const char elem[]);
    void    startElementLen(const char elem[], size_t length);
    void    writeDOM(const SkDOM&, const SkDOM::Node*, bool skipRoot);
    void    flush();
    virtual void writeHeader();

protected:
    virtual void onStartElementLen(const char elem[], size_t length) = 0;
    virtual void onAddAttributeLen(const char name[], const char value[], size_t length) = 0;
    virtual void onEndElement() = 0;

    struct Elem {
        SkString    fName;
        bool        fHasChildren;
    };
    void doEnd(Elem* elem);
    bool doStart(const char name[], size_t length);
    Elem* getEnd();
    const char* getHeader();
    SkTDArray<Elem*> fElems;

private:
    bool fDoEscapeMarkup;
    // illegal
    SkXMLWriter& operator=(const SkXMLWriter&);
};

class SkXMLStreamWriter : public SkXMLWriter {
public:
    SkXMLStreamWriter(SkWStream*);
    virtual ~SkXMLStreamWriter();
    virtual void    writeHeader();
    SkDEBUGCODE(static void UnitTest();)
protected:
    virtual void onStartElementLen(const char elem[], size_t length);
    virtual void onEndElement();
    virtual void onAddAttributeLen(const char name[], const char value[], size_t length);
private:
    SkWStream&      fStream;
};

class SkXMLParserWriter : public SkXMLWriter {
public:
    SkXMLParserWriter(SkXMLParser*);
    virtual ~SkXMLParserWriter();
protected:
    virtual void onStartElementLen(const char elem[], size_t length);
    virtual void onEndElement();
    virtual void onAddAttributeLen(const char name[], const char value[], size_t length);
private:
    SkXMLParser&        fParser;
};

#endif


code:
/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SkXfermode_DEFINED
#define SkXfermode_DEFINED

#include "SkFlattenable.h"
#include "SkColor.h"

/** \class SkXfermode

    SkXfermode is the base class for objects that are called to implement custom
    "transfer-modes" in the drawing pipeline. The static function Create(Modes)
    can be called to return an instance of any of the predefined subclasses as
    specified in the Modes enum. When an SkXfermode is assigned to an SkPaint,
    then objects drawn with that paint have the xfermode applied.
*/
class SK_API SkXfermode : public SkFlattenable {
public:
    SkXfermode() {}

    virtual void xfer32(SkPMColor dst[], const SkPMColor src[], int count,
                        const SkAlpha aa[]);
    virtual void xfer16(uint16_t dst[], const SkPMColor src[], int count,
                        const SkAlpha aa[]);
    virtual void xfer4444(uint16_t dst[], const SkPMColor src[], int count,
                          const SkAlpha aa[]);
    virtual void xferA8(SkAlpha dst[], const SkPMColor src[], int count,
                        const SkAlpha aa[]);

    /** Enum of possible coefficients to describe some xfermodes
     */
    enum Coeff {
        kZero_Coeff,    /** 0 */
        kOne_Coeff,     /** 1 */
        kSC_Coeff,      /** src color */
        kISC_Coeff,     /** inverse src color (i.e. 1 - sc) */
        kDC_Coeff,      /** dst color */
        kIDC_Coeff,     /** inverse dst color (i.e. 1 - dc) */
        kSA_Coeff,      /** src alpha */
        kISA_Coeff,     /** inverse src alpha (i.e. 1 - sa) */
        kDA_Coeff,      /** dst alpha */
        kIDA_Coeff,     /** inverse dst alpha (i.e. 1 - da) */

        kCoeffCount
    };

    /** If the xfermode can be expressed as an equation using the coefficients
        in Coeff, then asCoeff() returns true, and sets (if not null) src and
        dst accordingly.

            result = src_coeff * src_color + dst_coeff * dst_color;

        As examples, here are some of the porterduff coefficients

        MODE        SRC_COEFF       DST_COEFF
        clear       zero            zero
        src         one             zero
        dst         zero            one
        srcover     one             isa
        dstover     ida             one
     */
    virtual bool asCoeff(Coeff* src, Coeff* dst);

    /**
     *  The same as calling xfermode->asCoeff(..), except that this also checks
     *  if the xfermode is NULL, and if so, treats its as kSrcOver_Mode.
     */
    static bool AsCoeff(SkXfermode*, Coeff* src, Coeff* dst);

    /** List of predefined xfermodes.
        The algebra for the modes uses the following symbols:
        Sa, Sc  - source alpha and color
        Da, Dc - destination alpha and color (before compositing)
        [a, c] - Resulting (alpha, color) values
        For these equations, the colors are in premultiplied state.
        If no xfermode is specified, kSrcOver is assumed.
     */
    enum Mode {
        kClear_Mode,    //!< [0, 0]
        kSrc_Mode,      //!< [Sa, Sc]
        kDst_Mode,      //!< [Da, Dc]
        kSrcOver_Mode,  //!< [Sa + Da - Sa*Da, Rc = Sc + (1 - Sa)*Dc]
        kDstOver_Mode,  //!< [Sa + Da - Sa*Da, Rc = Dc + (1 - Da)*Sc]
        kSrcIn_Mode,    //!< [Sa * Da, Sc * Da]
        kDstIn_Mode,    //!< [Sa * Da, Sa * Dc]
        kSrcOut_Mode,   //!< [Sa * (1 - Da), Sc * (1 - Da)]
        kDstOut_Mode,   //!< [Da * (1 - Sa), Dc * (1 - Sa)]
        kSrcATop_Mode,  //!< [Da, Sc * Da + (1 - Sa) * Dc]
        kDstATop_Mode,  //!< [Sa, Sa * Dc + Sc * (1 - Da)]
        kXor_Mode,      //!< [Sa + Da - 2 * Sa * Da, Sc * (1 - Da) + (1 - Sa) * Dc]

        // all remaining modes are defined in the SVG Compositing standard
        // http://www.w3.org/TR/2009/WD-SVGCompositing-20090430/
        kPlus_Mode,
        kMultiply_Mode,

        // all above modes can be expressed as pair of src/dst Coeffs
        kCoeffModesCnt,

        kScreen_Mode = kCoeffModesCnt,
        kOverlay_Mode,
        kDarken_Mode,
        kLighten_Mode,
        kColorDodge_Mode,
        kColorBurn_Mode,
        kHardLight_Mode,
        kSoftLight_Mode,
        kDifference_Mode,
        kExclusion_Mode,

        kLastMode = kExclusion_Mode
    };

    /**
     *  If the xfermode is one of the modes in the Mode enum, then asMode()
     *  returns true and sets (if not null) mode accordingly. Otherwise it
     *  returns false and ignores the mode parameter.
     */
    virtual bool asMode(Mode* mode);

    /**
     *  The same as calling xfermode->asMode(mode), except that this also checks
     *  if the xfermode is NULL, and if so, treats its as kSrcOver_Mode.
     */
    static bool AsMode(SkXfermode*, Mode* mode);

    /** Return an SkXfermode object for the specified mode.
     */
    static SkXfermode* Create(Mode mode);

    /** Return a function pointer to a routine that applies the specified
        porter-duff transfer mode.
     */
    static SkXfermodeProc GetProc(Mode mode);

    /** Return a function pointer to a routine that applies the specified
        porter-duff transfer mode and srcColor to a 16bit device color. Note,
        if the mode+srcColor might return a non-opaque color, then there is not
        16bit proc, and this will return NULL.
      */
    static SkXfermodeProc16 GetProc16(Mode mode, SkColor srcColor);

    /**
     *  If the specified mode can be represented by a pair of Coeff, then return
     *  true and set (if not NULL) the corresponding coeffs. If the mode is
     *  not representable as a pair of Coeffs, return false and ignore the
     *  src and dst parameters.
     */
    static bool ModeAsCoeff(Mode mode, Coeff* src, Coeff* dst);

    // DEPRECATED: call AsMode(...)
    static bool IsMode(SkXfermode* xfer, Mode* mode) {
        return AsMode(xfer, mode);
    }

protected:
    SkXfermode(SkFlattenableReadBuffer& rb) : SkFlattenable(rb) {}

    /** The default implementation of xfer32/xfer16/xferA8 in turn call this
        method, 1 color at a time (upscaled to a SkPMColor). The default
        implmentation of this method just returns dst. If performance is
        important, your subclass should override xfer32/xfer16/xferA8 directly.

        This method will not be called directly by the client, so it need not
        be implemented if your subclass has overridden xfer32/xfer16/xferA8
    */
    virtual SkPMColor xferColor(SkPMColor src, SkPMColor dst);

private:
    enum {
        kModeCount = kLastMode + 1
    };
    typedef SkFlattenable INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

/** \class SkProcXfermode

    SkProcXfermode is a xfermode that applies the specified proc to its colors.
    This class is not exported to java.
*/
class SkProcXfermode : public SkXfermode {
public:
    SkProcXfermode(SkXfermodeProc proc) : fProc(proc) {}

    // overrides from SkXfermode
    virtual void xfer32(SkPMColor dst[], const SkPMColor src[], int count,
                        const SkAlpha aa[]);
    virtual void xfer16(uint16_t dst[], const SkPMColor src[], int count,
                        const SkAlpha aa[]);
    virtual void xfer4444(uint16_t dst[], const SkPMColor src[], int count,
                          const SkAlpha aa[]);
    virtual void xferA8(SkAlpha dst[], const SkPMColor src[], int count,
                        const SkAlpha aa[]);

    // overrides from SkFlattenable
    virtual Factory getFactory() { return CreateProc; }
    virtual void    flatten(SkFlattenableWriteBuffer&);

protected:
    SkProcXfermode(SkFlattenableReadBuffer&);

private:
    SkXfermodeProc  fProc;

    static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
        return SkNEW_ARGS(SkProcXfermode, (buffer)); }

    typedef SkXfermode INHERITED;
};

#endif


code:
#include "X11/Xlib.h"
#include "X11/keysym.h"

#include "SkKey.h"

#ifndef XKEYS_TOSKKEYS_H
#define XKEYS_TOSKKEYS_H

SkKey XKeyToSkKey(KeySym keysym) {
    switch (keysym) {
        case XK_BackSpace:
            return kBack_SkKey;
        case XK_Return:
            return kOK_SkKey;
        case XK_Home:
            return kHome_SkKey;
        case XK_End:
            return kEnd_SkKey;
        case XK_Right:
            return kRight_SkKey;
        case XK_Left:
            return kLeft_SkKey;
        case XK_Down:
            return kDown_SkKey;
        case XK_Up:
            return kUp_SkKey;
        default:
            return kNONE_SkKey;
    }
}
#endif


code:
/*
 * Copyright 2007, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef IMAGE_CODEC_BMPDECODERHELPER_H__
#define IMAGE_CODEC_BMPDECODERHELPER_H__

///////////////////////////////////////////////////////////////////////////////
// this section is my current "glue" between google3 code and android.
// will be fixed soon

#include "SkTypes.h"
#include <limits.h>
#define DISALLOW_EVIL_CONSTRUCTORS(name)
#define CHECK(predicate)  SkASSERT(predicate)
typedef uint8_t uint8;
typedef uint32_t uint32;

template <typename T> class scoped_array {
private:
  T* ptr_;
  scoped_array(scoped_array const&);
  scoped_array& operator=(const scoped_array&);

public:
  explicit scoped_array(T* p = 0) : ptr_(p) {}
  ~scoped_array() {
    delete[] ptr_;
  }

  void reset(T* p = 0) {
    if (p != ptr_) {
      delete[] ptr_;
      ptr_ = p;
    }
  }

  T& operator[](int i) const {
    return ptr_[i];
  }
};

///////////////////////////////////////////////////////////////////////////////

namespace image_codec {

class BmpDecoderCallback {
 public:
  BmpDecoderCallback() { }
  virtual ~BmpDecoderCallback() {}

  /**
   * This is called once for an image. It is passed the width and height and
   * should return the address of a buffer that is large enough to store
   * all of the resulting pixels (widht * height * 3 bytes). If it returns NULL,
   * then the decoder will abort, but return true, as the caller has received
   * valid dimensions.
   */
  virtual uint8* SetSize(int width, int height) = 0;

 private:
  DISALLOW_EVIL_CONSTRUCTORS(BmpDecoderCallback);
};

class BmpDecoderHelper {
 public:
  BmpDecoderHelper() { }
  ~BmpDecoderHelper() { }
  bool DecodeImage(const char* data,
                   int len,
                   int max_pixels,
                   BmpDecoderCallback* callback);

 private:
  DISALLOW_EVIL_CONSTRUCTORS(BmpDecoderHelper);

  void DoRLEDecode();
  void DoStandardDecode();
  void PutPixel(int x, int y, uint8 col);

  int GetInt();
  int GetShort();
  uint8 GetByte();
  int CalcShiftRight(uint32 mask);
  int CalcShiftLeft(uint32 mask);

  const uint8* data_;
  int pos_;
  int len_;
  int width_;
  int height_;
  int bpp_;
  int pixelPad_;
  int rowPad_;
  scoped_array<uint8> colTab_;
  uint32 redBits_;
  uint32 greenBits_;
  uint32 blueBits_;
  int redShiftRight_;
  int greenShiftRight_;
  int blueShiftRight_;
  int redShiftLeft_;
  int greenShiftLeft_;
  int blueShiftLeft_;
  uint8* output_;
  bool inverted_;
};

} // namespace

#endif