#include "Python.h" #include #include "frameobject.h" #include "expat.h" #include "pyexpat.h" #define XML_COMBINED_VERSION (10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION) #define FIX_TRACE enum HandlerTypes { StartElement, EndElement, ProcessingInstruction, CharacterData, UnparsedEntityDecl, NotationDecl, StartNamespaceDecl, EndNamespaceDecl, Comment, StartCdataSection, EndCdataSection, Default, DefaultHandlerExpand, NotStandalone, ExternalEntityRef, StartDoctypeDecl, EndDoctypeDecl, EntityDecl, XmlDecl, ElementDecl, AttlistDecl, #if XML_COMBINED_VERSION >= 19504 SkippedEntity, #endif _DummyDecl }; static PyObject *ErrorObject; /* ----------------------------------------------------- */ /* Declarations for objects of type xmlparser */ typedef struct { PyObject_HEAD XML_Parser itself; int ordered_attributes; /* Return attributes as a list. */ int specified_attributes; /* Report only specified attributes. */ int in_callback; /* Is a callback active? */ int ns_prefixes; /* Namespace-triplets mode? */ XML_Char *buffer; /* Buffer used when accumulating characters */ /* NULL if not enabled */ int buffer_size; /* Size of buffer, in XML_Char units */ int buffer_used; /* Buffer units in use */ PyObject *intern; /* Dictionary to intern strings */ PyObject **handlers; } xmlparseobject; #define CHARACTER_DATA_BUFFER_SIZE 8192 static PyTypeObject Xmlparsetype; typedef void (*xmlhandlersetter)(XML_Parser self, void *meth); typedef void* xmlhandler; struct HandlerInfo { const char *name; xmlhandlersetter setter; xmlhandler handler; PyCodeObject *tb_code; PyObject *nameobj; }; static struct HandlerInfo handler_info[64]; /* Set an integer attribute on the error object; return true on success, * false on an exception. */ static int set_error_attr(PyObject *err, char *name, int value) { PyObject *v = PyLong_FromLong(value); if (v == NULL || PyObject_SetAttrString(err, name, v) == -1) { Py_XDECREF(v); return 0; } Py_DECREF(v); return 1; } /* Build and set an Expat exception, including positioning * information. Always returns NULL. */ static PyObject * set_error(xmlparseobject *self, enum XML_Error code) { PyObject *err; char buffer[256]; XML_Parser parser = self->itself; int lineno = XML_GetErrorLineNumber(parser); int column = XML_GetErrorColumnNumber(parser); /* There is no risk of overflowing this buffer, since even for 64-bit integers, there is sufficient space. */ sprintf(buffer, "%.200s: line %i, column %i", XML_ErrorString(code), lineno, column); err = PyObject_CallFunction(ErrorObject, "s", buffer); if ( err != NULL && set_error_attr(err, "code", code) && set_error_attr(err, "offset", column) && set_error_attr(err, "lineno", lineno)) { PyErr_SetObject(ErrorObject, err); } Py_XDECREF(err); return NULL; } static int have_handler(xmlparseobject *self, int type) { PyObject *handler = self->handlers[type]; return handler != NULL; } static PyObject * get_handler_name(struct HandlerInfo *hinfo) { PyObject *name = hinfo->nameobj; if (name == NULL) { name = PyUnicode_FromString(hinfo->name); hinfo->nameobj = name; } Py_XINCREF(name); return name; } /* Convert a string of XML_Chars into a Unicode string. Returns None if str is a null pointer. */ static PyObject * conv_string_to_unicode(const XML_Char *str) { /* XXX currently this code assumes that XML_Char is 8-bit, and hence in UTF-8. */ /* UTF-8 from Expat, Unicode desired */ if (str == NULL) { Py_INCREF(Py_None); return Py_None; } return PyUnicode_DecodeUTF8(str, strlen(str), "strict"); } static PyObject * conv_string_len_to_unicode(const XML_Char *str, int len) { /* XXX currently this code assumes that XML_Char is 8-bit, and hence in UTF-8. */ /* UTF-8 from Expat, Unicode desired */ if (str == NULL) { Py_INCREF(Py_None); return Py_None; } return PyUnicode_DecodeUTF8((const char *)str, len, "strict"); } /* Callback routines */ static void clear_handlers(xmlparseobject *self, int initial); /* This handler is used when an error has been detected, in the hope that actual parsing can be terminated early. This will only help if an external entity reference is encountered. */ static int error_external_entity_ref_handler(XML_Parser parser, const XML_Char *context, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId) { return 0; } /* Dummy character data handler used when an error (exception) has been detected, and the actual parsing can be terminated early. This is needed since character data handler can't be safely removed from within the character data handler, but can be replaced. It is used only from the character data handler trampoline, and must be used right after `flag_error()` is called. */ static void noop_character_data_handler(void *userData, const XML_Char *data, int len) { /* Do nothing. */ } static void flag_error(xmlparseobject *self) { clear_handlers(self, 0); XML_SetExternalEntityRefHandler(self->itself, error_external_entity_ref_handler); } static PyCodeObject* getcode(enum HandlerTypes slot, char* func_name, int lineno) { PyObject *code = NULL; PyObject *name = NULL; PyObject *nulltuple = NULL; PyObject *filename = NULL; if (handler_info[slot].tb_code == NULL) { code = PyBytes_FromString(""); if (code == NULL) goto failed; name = PyUnicode_FromString(func_name); if (name == NULL) goto failed; nulltuple = PyTuple_New(0); if (nulltuple == NULL) goto failed; filename = PyUnicode_DecodeFSDefault(__FILE__); handler_info[slot].tb_code = PyCode_New(0, /* argcount */ 0, /* kwonlyargcount */ 0, /* nlocals */ 0, /* stacksize */ 0, /* flags */ code, /* code */ nulltuple, /* consts */ nulltuple, /* names */ nulltuple, /* varnames */ #if PYTHON_API_VERSION >= 1010 nulltuple, /* freevars */ nulltuple, /* cellvars */ #endif filename, /* filename */ name, /* name */ lineno, /* firstlineno */ code /* lnotab */ ); if (handler_info[slot].tb_code == NULL) goto failed; Py_DECREF(code); Py_DECREF(nulltuple); Py_DECREF(filename); Py_DECREF(name); } return handler_info[slot].tb_code; failed: Py_XDECREF(code); Py_XDECREF(name); return NULL; } #ifdef FIX_TRACE static int trace_frame(PyThreadState *tstate, PyFrameObject *f, int code, PyObject *val) { int result = 0; if (!tstate->use_tracing || tstate->tracing) return 0; if (tstate->c_profilefunc != NULL) { tstate->tracing++; result = tstate->c_profilefunc(tstate->c_profileobj, f, code , val); tstate->use_tracing = ((tstate->c_tracefunc != NULL) || (tstate->c_profilefunc != NULL)); tstate->tracing--; if (result) return result; } if (tstate->c_tracefunc != NULL) { tstate->tracing++; result = tstate->c_tracefunc(tstate->c_traceobj, f, code , val); tstate->use_tracing = ((tstate->c_tracefunc != NULL) || (tstate->c_profilefunc != NULL)); tstate->tracing--; } return result; } static int trace_frame_exc(PyThreadState *tstate, PyFrameObject *f) { PyObject *type, *value, *traceback, *arg; int err; if (tstate->c_tracefunc == NULL) return 0; PyErr_Fetch(&type, &value, &traceback); if (value == NULL) { value = Py_None; Py_INCREF(value); } #if PY_VERSION_HEX < 0x02040000 arg = Py_BuildValue("(OOO)", type, value, traceback); #else arg = PyTuple_Pack(3, type, value, traceback); #endif if (arg == NULL) { PyErr_Restore(type, value, traceback); return 0; } err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg); Py_DECREF(arg); if (err == 0) PyErr_Restore(type, value, traceback); else { Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); } return err; } #endif static PyObject* call_with_frame(PyCodeObject *c, PyObject* func, PyObject* args, xmlparseobject *self) { PyThreadState *tstate = PyThreadState_GET(); PyFrameObject *f; PyObject *res; if (c == NULL) return NULL; f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL); if (f == NULL) return NULL; tstate->frame = f; #ifdef FIX_TRACE if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) { return NULL; } #endif res = PyEval_CallObject(func, args); if (res == NULL) { if (tstate->curexc_traceback == NULL) PyTraceBack_Here(f); XML_StopParser(self->itself, XML_FALSE); #ifdef FIX_TRACE if (trace_frame_exc(tstate, f) < 0) { return NULL; } } else { if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) { Py_XDECREF(res); res = NULL; } } #else } #endif tstate->frame = f->f_back; Py_DECREF(f); return res; } static PyObject* string_intern(xmlparseobject *self, const char* str) { PyObject *result = conv_string_to_unicode(str); PyObject *value; /* result can be NULL if the unicode conversion failed. */ if (!result) return result; if (!self->intern) return result; value = PyDict_GetItem(self->intern, result); if (!value) { if (PyDict_SetItem(self->intern, result, result) == 0) return result; else return NULL; } Py_INCREF(value); Py_DECREF(result); return value; } /* Return 0 on success, -1 on exception. * flag_error() will be called before return if needed. */ static int call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len) { PyObject *args; PyObject *temp; args = PyTuple_New(1); if (args == NULL) return -1; temp = (conv_string_len_to_unicode(buffer, len)); if (temp == NULL) { Py_DECREF(args); flag_error(self); XML_SetCharacterDataHandler(self->itself, noop_character_data_handler); return -1; } PyTuple_SET_ITEM(args, 0, temp); /* temp is now a borrowed reference; consider it unused. */ self->in_callback = 1; temp = call_with_frame(getcode(CharacterData, "CharacterData", __LINE__), self->handlers[CharacterData], args, self); /* temp is an owned reference again, or NULL */ self->in_callback = 0; Py_DECREF(args); if (temp == NULL) { flag_error(self); XML_SetCharacterDataHandler(self->itself, noop_character_data_handler); return -1; } Py_DECREF(temp); return 0; } static int flush_character_buffer(xmlparseobject *self) { int rc; if (self->buffer == NULL || self->buffer_used == 0) return 0; rc = call_character_handler(self, self->buffer, self->buffer_used); self->buffer_used = 0; return rc; } static void my_CharacterDataHandler(void *userData, const XML_Char *data, int len) { xmlparseobject *self = (xmlparseobject *) userData; if (self->buffer == NULL) call_character_handler(self, data, len); else { if ((self->buffer_used + len) > self->buffer_size) { if (flush_character_buffer(self) < 0) return; /* handler might have changed; drop the rest on the floor * if there isn't a handler anymore */ if (!have_handler(self, CharacterData)) return; } if (len > self->buffer_size) { call_character_handler(self, data, len); self->buffer_used = 0; } else { memcpy(self->buffer + self->buffer_used, data, len * sizeof(XML_Char)); self->buffer_used += len; } } } static void my_StartElementHandler(void *userData, const XML_Char *name, const XML_Char *atts[]) { xmlparseobject *self = (xmlparseobject *)userData; if (have_handler(self, StartElement)) { PyObject *container, *rv, *args; int i, max; if (flush_character_buffer(self) < 0) return; /* Set max to the number of slots filled in atts[]; max/2 is * the number of attributes we need to process. */ if (self->specified_attributes) { max = XML_GetSpecifiedAttributeCount(self->itself); } else { max = 0; while (atts[max] != NULL) max += 2; } /* Build the container. */ if (self->ordered_attributes) container = PyList_New(max); else container = PyDict_New(); if (container == NULL) { flag_error(self); return; } for (i = 0; i < max; i += 2) { PyObject *n = string_intern(self, (XML_Char *) atts[i]); PyObject *v; if (n == NULL) { flag_error(self); Py_DECREF(container); return; } v = conv_string_to_unicode((XML_Char *) atts[i+1]); if (v == NULL) { flag_error(self); Py_DECREF(container); Py_DECREF(n); return; } if (self->ordered_attributes) { PyList_SET_ITEM(container, i, n); PyList_SET_ITEM(container, i+1, v); } else if (PyDict_SetItem(container, n, v)) { flag_error(self); Py_DECREF(n); Py_DECREF(v); return; } else { Py_DECREF(n); Py_DECREF(v); } } args = string_intern(self, name); if (args != NULL) args = Py_BuildValue("(NN)", args, container); if (args == NULL) { Py_DECREF(container); return; } /* Container is now a borrowed reference; ignore it. */ self->in_callback = 1; rv = call_with_frame(getcode(StartElement, "StartElement", __LINE__), self->handlers[StartElement], args, self); self->in_callback = 0; Py_DECREF(args); if (rv == NULL) { flag_error(self); return; } Py_DECREF(rv); } } #define RC_HANDLER(RC, NAME, PARAMS, INIT, PARAM_FORMAT, CONVERSION, \ RETURN, GETUSERDATA) \ static RC \ my_##NAME##Handler PARAMS {\ xmlparseobject *self = GETUSERDATA ; \ PyObject *args = NULL; \ PyObject *rv = NULL; \ INIT \ \ if (have_handler(self, NAME)) { \ if (flush_character_buffer(self) < 0) \ return RETURN; \ args = Py_BuildValue PARAM_FORMAT ;\ if (!args) { flag_error(self); return RETURN;} \ self->in_callback = 1; \ rv = call_with_frame(getcode(NAME,#NAME,__LINE__), \ self->handlers[NAME], args, self); \ self->in_callback = 0; \ Py_DECREF(args); \ if (rv == NULL) { \ flag_error(self); \ return RETURN; \ } \ CONVERSION \ Py_DECREF(rv); \ } \ return RETURN; \ } #define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \ RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\ (xmlparseobject *)userData) #define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\ RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \ rc = PyLong_AsLong(rv);, rc, \ (xmlparseobject *)userData) VOID_HANDLER(EndElement, (void *userData, const XML_Char *name), ("(N)", string_intern(self, name))) VOID_HANDLER(ProcessingInstruction, (void *userData, const XML_Char *target, const XML_Char *data), ("(NO&)", string_intern(self, target), conv_string_to_unicode ,data)) VOID_HANDLER(UnparsedEntityDecl, (void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName), ("(NNNNN)", string_intern(self, entityName), string_intern(self, base), string_intern(self, systemId), string_intern(self, publicId), string_intern(self, notationName))) VOID_HANDLER(EntityDecl, (void *userData, const XML_Char *entityName, int is_parameter_entity, const XML_Char *value, int value_length, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName), ("NiNNNNN", string_intern(self, entityName), is_parameter_entity, (conv_string_len_to_unicode(value, value_length)), string_intern(self, base), string_intern(self, systemId), string_intern(self, publicId), string_intern(self, notationName))) VOID_HANDLER(XmlDecl, (void *userData, const XML_Char *version, const XML_Char *encoding, int standalone), ("(O&O&i)", conv_string_to_unicode ,version, conv_string_to_unicode ,encoding, standalone)) static PyObject * conv_content_model(XML_Content * const model, PyObject *(*conv_string)(const XML_Char *)) { PyObject *result = NULL; PyObject *children = PyTuple_New(model->numchildren); int i; if (children != NULL) { assert(model->numchildren < INT_MAX); for (i = 0; i < (int)model->numchildren; ++i) { PyObject *child = conv_content_model(&model->children[i], conv_string); if (child == NULL) { Py_XDECREF(children); return NULL; } PyTuple_SET_ITEM(children, i, child); } result = Py_BuildValue("(iiO&N)", model->type, model->quant, conv_string,model->name, children); } return result; } static void my_ElementDeclHandler(void *userData, const XML_Char *name, XML_Content *model) { xmlparseobject *self = (xmlparseobject *)userData; PyObject *args = NULL; if (have_handler(self, ElementDecl)) { PyObject *rv = NULL; PyObject *modelobj, *nameobj; if (flush_character_buffer(self) < 0) goto finally; modelobj = conv_content_model(model, (conv_string_to_unicode)); if (modelobj == NULL) { flag_error(self); goto finally; } nameobj = string_intern(self, name); if (nameobj == NULL) { Py_DECREF(modelobj); flag_error(self); goto finally; } args = Py_BuildValue("NN", nameobj, modelobj); if (args == NULL) { Py_DECREF(modelobj); flag_error(self); goto finally; } self->in_callback = 1; rv = call_with_frame(getcode(ElementDecl, "ElementDecl", __LINE__), self->handlers[ElementDecl], args, self); self->in_callback = 0; if (rv == NULL) { flag_error(self); goto finally; } Py_DECREF(rv); } finally: Py_XDECREF(args); XML_FreeContentModel(self->itself, model); return; } VOID_HANDLER(AttlistDecl, (void *userData, const XML_Char *elname, const XML_Char *attname, const XML_Char *att_type, const XML_Char *dflt, int isrequired), ("(NNO&O&i)", string_intern(self, elname), string_intern(self, attname), conv_string_to_unicode ,att_type, conv_string_to_unicode ,dflt, isrequired)) #if XML_COMBINED_VERSION >= 19504 VOID_HANDLER(SkippedEntity, (void *userData, const XML_Char *entityName, int is_parameter_entity), ("Ni", string_intern(self, entityName), is_parameter_entity)) #endif VOID_HANDLER(NotationDecl, (void *userData, const XML_Char *notationName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId), ("(NNNN)", string_intern(self, notationName), string_intern(self, base), string_intern(self, systemId), string_intern(self, publicId))) VOID_HANDLER(StartNamespaceDecl, (void *userData, const XML_Char *prefix, const XML_Char *uri), ("(NN)", string_intern(self, prefix), string_intern(self, uri))) VOID_HANDLER(EndNamespaceDecl, (void *userData, const XML_Char *prefix), ("(N)", string_intern(self, prefix))) VOID_HANDLER(Comment, (void *userData, const XML_Char *data), ("(O&)", conv_string_to_unicode ,data)) VOID_HANDLER(StartCdataSection, (void *userData), ("()")) VOID_HANDLER(EndCdataSection, (void *userData), ("()")) VOID_HANDLER(Default, (void *userData, const XML_Char *s, int len), ("(N)", (conv_string_len_to_unicode(s,len)))) VOID_HANDLER(DefaultHandlerExpand, (void *userData, const XML_Char *s, int len), ("(N)", (conv_string_len_to_unicode(s,len)))) INT_HANDLER(NotStandalone, (void *userData), ("()")) RC_HANDLER(int, ExternalEntityRef, (XML_Parser parser, const XML_Char *context, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId), int rc=0;, ("(O&NNN)", conv_string_to_unicode ,context, string_intern(self, base), string_intern(self, systemId), string_intern(self, publicId)), rc = PyLong_AsLong(rv);, rc, XML_GetUserData(parser)) /* XXX UnknownEncodingHandler */ VOID_HANDLER(StartDoctypeDecl, (void *userData, const XML_Char *doctypeName, const XML_Char *sysid, const XML_Char *pubid, int has_internal_subset), ("(NNNi)", string_intern(self, doctypeName), string_intern(self, sysid), string_intern(self, pubid), has_internal_subset)) VOID_HANDLER(EndDoctypeDecl, (void *userData), ("()")) /* ---------------------------------------------------------------- */ static PyObject * get_parse_result(xmlparseobject *self, int rv) { if (PyErr_Occurred()) { return NULL; } if (rv == 0) { return set_error(self, XML_GetErrorCode(self->itself)); } if (flush_character_buffer(self) < 0) { return NULL; } return PyLong_FromLong(rv); } PyDoc_STRVAR(xmlparse_Parse__doc__, "Parse(data[, isfinal])\n\ Parse XML data. `isfinal' should be true at end of input."); static PyObject * xmlparse_Parse(xmlparseobject *self, PyObject *args) { char *s; int slen; int isFinal = 0; if (!PyArg_ParseTuple(args, "s#|i:Parse", &s, &slen, &isFinal)) return NULL; return get_parse_result(self, XML_Parse(self->itself, s, slen, isFinal)); } /* File reading copied from cPickle */ #define BUF_SIZE 2048 static int readinst(char *buf, int buf_size, PyObject *meth) { PyObject *arg = NULL; PyObject *bytes = NULL; PyObject *str = NULL; int len = -1; char *ptr; if ((bytes = PyLong_FromLong(buf_size)) == NULL) goto finally; if ((arg = PyTuple_New(1)) == NULL) { Py_DECREF(bytes); goto finally; } PyTuple_SET_ITEM(arg, 0, bytes); #if PY_VERSION_HEX < 0x02020000 str = PyObject_CallObject(meth, arg); #else str = PyObject_Call(meth, arg, NULL); #endif if (str == NULL) goto finally; if (PyBytes_Check(str)) ptr = PyBytes_AS_STRING(str); else if (PyByteArray_Check(str)) ptr = PyByteArray_AS_STRING(str); else { PyErr_Format(PyExc_TypeError, "read() did not return a bytes object (type=%.400s)", Py_TYPE(str)->tp_name); goto finally; } len = Py_SIZE(str); if (len > buf_size) { PyErr_Format(PyExc_ValueError, "read() returned too much data: " "%i bytes requested, %i returned", buf_size, len); goto finally; } memcpy(buf, ptr, len); finally: Py_XDECREF(arg); Py_XDECREF(str); return len; } PyDoc_STRVAR(xmlparse_ParseFile__doc__, "ParseFile(file)\n\ Parse XML data from file-like object."); static PyObject * xmlparse_ParseFile(xmlparseobject *self, PyObject *f) { int rv = 1; FILE *fp; PyObject *readmethod = NULL; { fp = NULL; readmethod = PyObject_GetAttrString(f, "read"); if (readmethod == NULL) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "argument must have 'read' attribute"); return NULL; } } for (;;) { int bytes_read; void *buf = XML_GetBuffer(self->itself, BUF_SIZE); if (buf == NULL) { Py_XDECREF(readmethod); return PyErr_NoMemory(); } if (fp) { bytes_read = fread(buf, sizeof(char), BUF_SIZE, fp); if (bytes_read < 0) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } } else { bytes_read = readinst(buf, BUF_SIZE, readmethod); if (bytes_read < 0) { Py_DECREF(readmethod); return NULL; } } rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0); if (PyErr_Occurred()) { Py_XDECREF(readmethod); return NULL; } if (!rv || bytes_read == 0) break; } Py_XDECREF(readmethod); return get_parse_result(self, rv); } PyDoc_STRVAR(xmlparse_SetBase__doc__, "SetBase(base_url)\n\ Set the base URL for the parser."); static PyObject * xmlparse_SetBase(xmlparseobject *self, PyObject *args) { char *base; if (!PyArg_ParseTuple(args, "s:SetBase", &base)) return NULL; if (!XML_SetBase(self->itself, base)) { return PyErr_NoMemory(); } Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(xmlparse_GetBase__doc__, "GetBase() -> url\n\ Return base URL string for the parser."); static PyObject * xmlparse_GetBase(xmlparseobject *self, PyObject *unused) { return Py_BuildValue("z", XML_GetBase(self->itself)); } PyDoc_STRVAR(xmlparse_GetInputContext__doc__, "GetInputContext() -> string\n\ Return the untranslated text of the input that caused the current event.\n\ If the event was generated by a large amount of text (such as a start tag\n\ for an element with many attributes), not all of the text may be available."); static PyObject * xmlparse_GetInputContext(xmlparseobject *self, PyObject *unused) { if (self->in_callback) { int offset, size; const char *buffer = XML_GetInputContext(self->itself, &offset, &size); if (buffer != NULL) return PyBytes_FromStringAndSize(buffer + offset, size - offset); else Py_RETURN_NONE; } else Py_RETURN_NONE; } PyDoc_STRVAR(xmlparse_ExternalEntityParserCreate__doc__, "ExternalEntityParserCreate(context[, encoding])\n\ Create a parser for parsing an external entity based on the\n\ information passed to the ExternalEntityRefHandler."); static PyObject * xmlparse_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args) { char *context; char *encoding = NULL; xmlparseobject *new_parser; int i; if (!PyArg_ParseTuple(args, "z|s:ExternalEntityParserCreate", &context, &encoding)) { return NULL; } #ifndef Py_TPFLAGS_HAVE_GC /* Python versions 2.0 and 2.1 */ new_parser = PyObject_New(xmlparseobject, &Xmlparsetype); #else /* Python versions 2.2 and later */ new_parser = PyObject_GC_New(xmlparseobject, &Xmlparsetype); #endif if (new_parser == NULL) return NULL; new_parser->buffer_size = self->buffer_size; new_parser->buffer_used = 0; if (self->buffer != NULL) { new_parser->buffer = malloc(new_parser->buffer_size); if (new_parser->buffer == NULL) { #ifndef Py_TPFLAGS_HAVE_GC /* Code for versions 2.0 and 2.1 */ PyObject_Del(new_parser); #else /* Code for versions 2.2 and later. */ PyObject_GC_Del(new_parser); #endif return PyErr_NoMemory(); } } else new_parser->buffer = NULL; new_parser->ordered_attributes = self->ordered_attributes; new_parser->specified_attributes = self->specified_attributes; new_parser->in_callback = 0; new_parser->ns_prefixes = self->ns_prefixes; new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context, encoding); new_parser->handlers = 0; new_parser->intern = self->intern; Py_XINCREF(new_parser->intern); #ifdef Py_TPFLAGS_HAVE_GC PyObject_GC_Track(new_parser); #else PyObject_GC_Init(new_parser); #endif if (!new_parser->itself) { Py_DECREF(new_parser); return PyErr_NoMemory(); } XML_SetUserData(new_parser->itself, (void *)new_parser); /* allocate and clear handlers first */ for (i = 0; handler_info[i].name != NULL; i++) /* do nothing */; new_parser->handlers = malloc(sizeof(PyObject *) * i); if (!new_parser->handlers) { Py_DECREF(new_parser); return PyErr_NoMemory(); } clear_handlers(new_parser, 1); /* then copy handlers from self */ for (i = 0; handler_info[i].name != NULL; i++) { PyObject *handler = self->handlers[i]; if (handler != NULL) { Py_INCREF(handler); new_parser->handlers[i] = handler; handler_info[i].setter(new_parser->itself, handler_info[i].handler); } } return (PyObject *)new_parser; } PyDoc_STRVAR(xmlparse_SetParamEntityParsing__doc__, "SetParamEntityParsing(flag) -> success\n\ Controls parsing of parameter entities (including the external DTD\n\ subset). Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,\n\ XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and\n\ XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag\n\ was successful."); static PyObject* xmlparse_SetParamEntityParsing(xmlparseobject *p, PyObject* args) { int flag; if (!PyArg_ParseTuple(args, "i", &flag)) return NULL; flag = XML_SetParamEntityParsing(p->itself, flag); return PyLong_FromLong(flag); } #if XML_COMBINED_VERSION >= 19505 PyDoc_STRVAR(xmlparse_UseForeignDTD__doc__, "UseForeignDTD([flag])\n\ Allows the application to provide an artificial external subset if one is\n\ not specified as part of the document instance. This readily allows the\n\ use of a 'default' document type controlled by the application, while still\n\ getting the advantage of providing document type information to the parser.\n\ 'flag' defaults to True if not provided."); static PyObject * xmlparse_UseForeignDTD(xmlparseobject *self, PyObject *args) { PyObject *flagobj = NULL; XML_Bool flag = XML_TRUE; enum XML_Error rc; if (!PyArg_UnpackTuple(args, "UseForeignDTD", 0, 1, &flagobj)) return NULL; if (flagobj != NULL) flag = PyObject_IsTrue(flagobj) ? XML_TRUE : XML_FALSE; rc = XML_UseForeignDTD(self->itself, flag); if (rc != XML_ERROR_NONE) { return set_error(self, rc); } Py_INCREF(Py_None); return Py_None; } #endif static PyObject *xmlparse_dir(PyObject *self, PyObject* noargs); static struct PyMethodDef xmlparse_methods[] = { {"Parse", (PyCFunction)xmlparse_Parse, METH_VARARGS, xmlparse_Parse__doc__}, {"ParseFile", (PyCFunction)xmlparse_ParseFile, METH_O, xmlparse_ParseFile__doc__}, {"SetBase", (PyCFunction)xmlparse_SetBase, METH_VARARGS, xmlparse_SetBase__doc__}, {"GetBase", (PyCFunction)xmlparse_GetBase, METH_NOARGS, xmlparse_GetBase__doc__}, {"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate, METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__}, {"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing, METH_VARARGS, xmlparse_SetParamEntityParsing__doc__}, {"GetInputContext", (PyCFunction)xmlparse_GetInputContext, METH_NOARGS, xmlparse_GetInputContext__doc__}, #if XML_COMBINED_VERSION >= 19505 {"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD, METH_VARARGS, xmlparse_UseForeignDTD__doc__}, #endif {"__dir__", xmlparse_dir, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; /* ---------- */ /* pyexpat international encoding support. Make it as simple as possible. */ static char template_buffer[257]; static void init_template_buffer(void) { int i; for (i = 0; i < 256; i++) { template_buffer[i] = i; } template_buffer[256] = 0; } static int PyUnknownEncodingHandler(void *encodingHandlerData, const XML_Char *name, XML_Encoding *info) { PyUnicodeObject *_u_string = NULL; int result = 0; int i; /* Yes, supports only 8bit encodings */ _u_string = (PyUnicodeObject *) PyUnicode_Decode(template_buffer, 256, name, "replace"); if (_u_string == NULL) return result; for (i = 0; i < 256; i++) { /* Stupid to access directly, but fast */ Py_UNICODE c = _u_string->str[i]; if (c == Py_UNICODE_REPLACEMENT_CHARACTER) info->map[i] = -1; else info->map[i] = c; } info->data = NULL; info->convert = NULL; info->release = NULL; result = 1; Py_DECREF(_u_string); return result; } static PyObject * newxmlparseobject(char *encoding, char *namespace_separator, PyObject *intern) { int i; xmlparseobject *self; #ifdef Py_TPFLAGS_HAVE_GC /* Code for versions 2.2 and later */ self = PyObject_GC_New(xmlparseobject, &Xmlparsetype); #else self = PyObject_New(xmlparseobject, &Xmlparsetype); #endif if (self == NULL) return NULL; self->buffer = NULL; self->buffer_size = CHARACTER_DATA_BUFFER_SIZE; self->buffer_used = 0; self->ordered_attributes = 0; self->specified_attributes = 0; self->in_callback = 0; self->ns_prefixes = 0; self->handlers = NULL; if (namespace_separator != NULL) { self->itself = XML_ParserCreateNS(encoding, *namespace_separator); } else { self->itself = XML_ParserCreate(encoding); } self->intern = intern; Py_XINCREF(self->intern); #ifdef Py_TPFLAGS_HAVE_GC PyObject_GC_Track(self); #else PyObject_GC_Init(self); #endif if (self->itself == NULL) { PyErr_SetString(PyExc_RuntimeError, "XML_ParserCreate failed"); Py_DECREF(self); return NULL; } XML_SetUserData(self->itself, (void *)self); XML_SetUnknownEncodingHandler(self->itself, (XML_UnknownEncodingHandler) PyUnknownEncodingHandler, NULL); for (i = 0; handler_info[i].name != NULL; i++) /* do nothing */; self->handlers = malloc(sizeof(PyObject *) * i); if (!self->handlers) { Py_DECREF(self); return PyErr_NoMemory(); } clear_handlers(self, 1); return (PyObject*)self; } static void xmlparse_dealloc(xmlparseobject *self) { int i; #ifdef Py_TPFLAGS_HAVE_GC PyObject_GC_UnTrack(self); #else PyObject_GC_Fini(self); #endif if (self->itself != NULL) XML_ParserFree(self->itself); self->itself = NULL; if (self->handlers != NULL) { PyObject *temp; for (i = 0; handler_info[i].name != NULL; i++) { temp = self->handlers[i]; self->handlers[i] = NULL; Py_XDECREF(temp); } free(self->handlers); self->handlers = NULL; } if (self->buffer != NULL) { free(self->buffer); self->buffer = NULL; } Py_XDECREF(self->intern); #ifndef Py_TPFLAGS_HAVE_GC /* Code for versions 2.0 and 2.1 */ PyObject_Del(self); #else /* Code for versions 2.2 and later. */ PyObject_GC_Del(self); #endif } static int handlername2int(const char *name) { int i; for (i = 0; handler_info[i].name != NULL; i++) { if (strcmp(name, handler_info[i].name) == 0) { return i; } } return -1; } static PyObject * get_pybool(int istrue) { PyObject *result = istrue ? Py_True : Py_False; Py_INCREF(result); return result; } static PyObject * xmlparse_getattro(xmlparseobject *self, PyObject *nameobj) { char *name = ""; int handlernum = -1; if (PyUnicode_Check(nameobj)) name = _PyUnicode_AsString(nameobj); handlernum = handlername2int(name); if (handlernum != -1) { PyObject *result = self->handlers[handlernum]; if (result == NULL) result = Py_None; Py_INCREF(result); return result; } if (name[0] == 'E') { if (strcmp(name, "ErrorCode") == 0) return PyLong_FromLong((long) XML_GetErrorCode(self->itself)); if (strcmp(name, "ErrorLineNumber") == 0) return PyLong_FromLong((long) XML_GetErrorLineNumber(self->itself)); if (strcmp(name, "ErrorColumnNumber") == 0) return PyLong_FromLong((long) XML_GetErrorColumnNumber(self->itself)); if (strcmp(name, "ErrorByteIndex") == 0) return PyLong_FromLong((long) XML_GetErrorByteIndex(self->itself)); } if (name[0] == 'C') { if (strcmp(name, "CurrentLineNumber") == 0) return PyLong_FromLong((long) XML_GetCurrentLineNumber(self->itself)); if (strcmp(name, "CurrentColumnNumber") == 0) return PyLong_FromLong((long) XML_GetCurrentColumnNumber(self->itself)); if (strcmp(name, "CurrentByteIndex") == 0) return PyLong_FromLong((long) XML_GetCurrentByteIndex(self->itself)); } if (name[0] == 'b') { if (strcmp(name, "buffer_size") == 0) return PyLong_FromLong((long) self->buffer_size); if (strcmp(name, "buffer_text") == 0) return get_pybool(self->buffer != NULL); if (strcmp(name, "buffer_used") == 0) return PyLong_FromLong((long) self->buffer_used); } if (strcmp(name, "namespace_prefixes") == 0) return get_pybool(self->ns_prefixes); if (strcmp(name, "ordered_attributes") == 0) return get_pybool(self->ordered_attributes); if (strcmp(name, "specified_attributes") == 0) return get_pybool((long) self->specified_attributes); if (strcmp(name, "intern") == 0) { if (self->intern == NULL) { Py_INCREF(Py_None); return Py_None; } else { Py_INCREF(self->intern); return self->intern; } } return PyObject_GenericGetAttr((PyObject*)self, nameobj); } static PyObject * xmlparse_dir(PyObject *self, PyObject* noargs) { #define APPEND(list, str) \ do { \ PyObject *o = PyUnicode_FromString(str); \ if (o != NULL) \ PyList_Append(list, o); \ Py_XDECREF(o); \ } while (0) int i; PyObject *rc = PyList_New(0); if (!rc) return NULL; for (i = 0; handler_info[i].name != NULL; i++) { PyObject *o = get_handler_name(&handler_info[i]); if (o != NULL) PyList_Append(rc, o); Py_XDECREF(o); } APPEND(rc, "ErrorCode"); APPEND(rc, "ErrorLineNumber"); APPEND(rc, "ErrorColumnNumber"); APPEND(rc, "ErrorByteIndex"); APPEND(rc, "CurrentLineNumber"); APPEND(rc, "CurrentColumnNumber"); APPEND(rc, "CurrentByteIndex"); APPEND(rc, "buffer_size"); APPEND(rc, "buffer_text"); APPEND(rc, "buffer_used"); APPEND(rc, "namespace_prefixes"); APPEND(rc, "ordered_attributes"); APPEND(rc, "specified_attributes"); APPEND(rc, "intern"); #undef APPEND if (PyErr_Occurred()) { Py_DECREF(rc); rc = NULL; } return rc; } static int sethandler(xmlparseobject *self, const char *name, PyObject* v) { int handlernum = handlername2int(name); if (handlernum >= 0) { xmlhandler c_handler = NULL; PyObject *temp = self->handlers[handlernum]; if (v == Py_None) { /* If this is the character data handler, and a character data handler is already active, we need to be more careful. What we can safely do is replace the existing character data handler callback function with a no-op function that will refuse to call Python. The downside is that this doesn't completely remove the character data handler from the C layer if there's any callback active, so Expat does a little more work than it otherwise would, but that's really an odd case. A more elaborate system of handlers and state could remove the C handler more effectively. */ if (handlernum == CharacterData && self->in_callback) c_handler = noop_character_data_handler; v = NULL; } else if (v != NULL) { Py_INCREF(v); c_handler = handler_info[handlernum].handler; } self->handlers[handlernum] = v; Py_XDECREF(temp); handler_info[handlernum].setter(self->itself, c_handler); return 1; } return 0; } static int xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v) { /* Set attribute 'name' to value 'v'. v==NULL means delete */ if (v == NULL) { PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute"); return -1; } if (strcmp(name, "buffer_text") == 0) { if (PyObject_IsTrue(v)) { if (self->buffer == NULL) { self->buffer = malloc(self->buffer_size); if (self->buffer == NULL) { PyErr_NoMemory(); return -1; } self->buffer_used = 0; } } else if (self->buffer != NULL) { if (flush_character_buffer(self) < 0) return -1; free(self->buffer); self->buffer = NULL; } return 0; } if (strcmp(name, "namespace_prefixes") == 0) { if (PyObject_IsTrue(v)) self->ns_prefixes = 1; else self->ns_prefixes = 0; XML_SetReturnNSTriplet(self->itself, self->ns_prefixes); return 0; } if (strcmp(name, "ordered_attributes") == 0) { if (PyObject_IsTrue(v)) self->ordered_attributes = 1; else self->ordered_attributes = 0; return 0; } if (strcmp(name, "specified_attributes") == 0) { if (PyObject_IsTrue(v)) self->specified_attributes = 1; else self->specified_attributes = 0; return 0; } if (strcmp(name, "buffer_size") == 0) { long new_buffer_size; if (!PyLong_Check(v)) { PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer"); return -1; } new_buffer_size=PyLong_AS_LONG(v); /* trivial case -- no change */ if (new_buffer_size == self->buffer_size) { return 0; } if (new_buffer_size <= 0) { PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero"); return -1; } /* check maximum */ if (new_buffer_size > INT_MAX) { char errmsg[100]; sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX); PyErr_SetString(PyExc_ValueError, errmsg); return -1; } if (self->buffer != NULL) { /* there is already a buffer */ if (self->buffer_used != 0) { flush_character_buffer(self); } /* free existing buffer */ free(self->buffer); } self->buffer = malloc(new_buffer_size); if (self->buffer == NULL) { PyErr_NoMemory(); return -1; } self->buffer_size = new_buffer_size; return 0; } if (strcmp(name, "CharacterDataHandler") == 0) { /* If we're changing the character data handler, flush all * cached data with the old handler. Not sure there's a * "right" thing to do, though, but this probably won't * happen. */ if (flush_character_buffer(self) < 0) return -1; } if (sethandler(self, name, v)) { return 0; } PyErr_SetString(PyExc_AttributeError, name); return -1; } static int xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg) { int i; for (i = 0; handler_info[i].name != NULL; i++) Py_VISIT(op->handlers[i]); return 0; } static int xmlparse_clear(xmlparseobject *op) { clear_handlers(op, 0); Py_CLEAR(op->intern); return 0; } PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser"); static PyTypeObject Xmlparsetype = { PyVarObject_HEAD_INIT(NULL, 0) "pyexpat.xmlparser", /*tp_name*/ sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ (destructor)xmlparse_dealloc, /*tp_dealloc*/ (printfunc)0, /*tp_print*/ 0, /*tp_getattr*/ (setattrfunc)xmlparse_setattr, /*tp_setattr*/ 0, /*tp_reserved*/ (reprfunc)0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ (hashfunc)0, /*tp_hash*/ (ternaryfunc)0, /*tp_call*/ (reprfunc)0, /*tp_str*/ (getattrofunc)xmlparse_getattro, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ #ifdef Py_TPFLAGS_HAVE_GC Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ #else Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ #endif Xmlparsetype__doc__, /* tp_doc - Documentation string */ (traverseproc)xmlparse_traverse, /* tp_traverse */ (inquiry)xmlparse_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ xmlparse_methods, /* tp_methods */ }; /* End of code for xmlparser objects */ /* -------------------------------------------------------- */ PyDoc_STRVAR(pyexpat_ParserCreate__doc__, "ParserCreate([encoding[, namespace_separator]]) -> parser\n\ Return a new XML parser object."); static PyObject * pyexpat_ParserCreate(PyObject *notused, PyObject *args, PyObject *kw) { char *encoding = NULL; char *namespace_separator = NULL; PyObject *intern = NULL; PyObject *result; int intern_decref = 0; static char *kwlist[] = {"encoding", "namespace_separator", "intern", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kw, "|zzO:ParserCreate", kwlist, &encoding, &namespace_separator, &intern)) return NULL; if (namespace_separator != NULL && strlen(namespace_separator) > 1) { PyErr_SetString(PyExc_ValueError, "namespace_separator must be at most one" " character, omitted, or None"); return NULL; } /* Explicitly passing None means no interning is desired. Not passing anything means that a new dictionary is used. */ if (intern == Py_None) intern = NULL; else if (intern == NULL) { intern = PyDict_New(); if (!intern) return NULL; intern_decref = 1; } else if (!PyDict_Check(intern)) { PyErr_SetString(PyExc_TypeError, "intern must be a dictionary"); return NULL; } result = newxmlparseobject(encoding, namespace_separator, intern); if (intern_decref) { Py_DECREF(intern); } return result; } PyDoc_STRVAR(pyexpat_ErrorString__doc__, "ErrorString(errno) -> string\n\ Returns string error for given number."); static PyObject * pyexpat_ErrorString(PyObject *self, PyObject *args) { long code = 0; if (!PyArg_ParseTuple(args, "l:ErrorString", &code)) return NULL; return Py_BuildValue("z", XML_ErrorString((int)code)); } /* List of methods defined in the module */ static struct PyMethodDef pyexpat_methods[] = { {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__}, {"ErrorString", (PyCFunction)pyexpat_ErrorString, METH_VARARGS, pyexpat_ErrorString__doc__}, {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */ }; /* Module docstring */ PyDoc_STRVAR(pyexpat_module_documentation, "Python wrapper for Expat parser."); /* Return a Python string that represents the version number without the * extra cruft added by revision control, even if the right options were * given to the "cvs export" command to make it not include the extra * cruft. */ static PyObject * get_version_string(void) { static char *rcsid = "$Revision$"; char *rev = rcsid; int i = 0; while (!isdigit(Py_CHARMASK(*rev))) ++rev; while (rev[i] != ' ' && rev[i] != '\0') ++i; return PyUnicode_FromStringAndSize(rev, i); } /* Initialization function for the module */ #ifndef MODULE_NAME #define MODULE_NAME "pyexpat" #endif #ifndef MODULE_INITFUNC #define MODULE_INITFUNC PyInit_pyexpat #endif #ifndef PyMODINIT_FUNC # ifdef MS_WINDOWS # define PyMODINIT_FUNC __declspec(dllexport) void # else # define PyMODINIT_FUNC void # endif #endif PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */ static struct PyModuleDef pyexpatmodule = { PyModuleDef_HEAD_INIT, MODULE_NAME, pyexpat_module_documentation, -1, pyexpat_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC MODULE_INITFUNC(void) { PyObject *m, *d; PyObject *errmod_name = PyUnicode_FromString(MODULE_NAME ".errors"); PyObject *errors_module; PyObject *modelmod_name; PyObject *model_module; PyObject *sys_modules; static struct PyExpat_CAPI capi; PyObject* capi_object; if (errmod_name == NULL) return NULL; modelmod_name = PyUnicode_FromString(MODULE_NAME ".model"); if (modelmod_name == NULL) return NULL; if (PyType_Ready(&Xmlparsetype) < 0) return NULL; /* Create the module and add the functions */ m = PyModule_Create(&pyexpatmodule); if (m == NULL) return NULL; /* Add some symbolic constants to the module */ if (ErrorObject == NULL) { ErrorObject = PyErr_NewException("xml.parsers.expat.ExpatError", NULL, NULL); if (ErrorObject == NULL) return NULL; } Py_INCREF(ErrorObject); PyModule_AddObject(m, "error", ErrorObject); Py_INCREF(ErrorObject); PyModule_AddObject(m, "ExpatError", ErrorObject); Py_INCREF(&Xmlparsetype); PyModule_AddObject(m, "XMLParserType", (PyObject *) &Xmlparsetype); PyModule_AddObject(m, "__version__", get_version_string()); PyModule_AddStringConstant(m, "EXPAT_VERSION", (char *) XML_ExpatVersion()); { XML_Expat_Version info = XML_ExpatVersionInfo(); PyModule_AddObject(m, "version_info", Py_BuildValue("(iii)", info.major, info.minor, info.micro)); } init_template_buffer(); /* XXX When Expat supports some way of figuring out how it was compiled, this should check and set native_encoding appropriately. */ PyModule_AddStringConstant(m, "native_encoding", "UTF-8"); sys_modules = PySys_GetObject("modules"); d = PyModule_GetDict(m); errors_module = PyDict_GetItem(d, errmod_name); if (errors_module == NULL) { errors_module = PyModule_New(MODULE_NAME ".errors"); if (errors_module != NULL) { PyDict_SetItem(sys_modules, errmod_name, errors_module); /* gives away the reference to errors_module */ PyModule_AddObject(m, "errors", errors_module); } } Py_DECREF(errmod_name); model_module = PyDict_GetItem(d, modelmod_name); if (model_module == NULL) { model_module = PyModule_New(MODULE_NAME ".model"); if (model_module != NULL) { PyDict_SetItem(sys_modules, modelmod_name, model_module); /* gives away the reference to model_module */ PyModule_AddObject(m, "model", model_module); } } Py_DECREF(modelmod_name); if (errors_module == NULL || model_module == NULL) /* Don't core dump later! */ return NULL; #if XML_COMBINED_VERSION > 19505 { const XML_Feature *features = XML_GetFeatureList(); PyObject *list = PyList_New(0); if (list == NULL) /* just ignore it */ PyErr_Clear(); else { int i = 0; for (; features[i].feature != XML_FEATURE_END; ++i) { int ok; PyObject *item = Py_BuildValue("si", features[i].name, features[i].value); if (item == NULL) { Py_DECREF(list); list = NULL; break; } ok = PyList_Append(list, item); Py_DECREF(item); if (ok < 0) { PyErr_Clear(); break; } } if (list != NULL) PyModule_AddObject(m, "features", list); } } #endif #define MYCONST(name) \ PyModule_AddStringConstant(errors_module, #name, \ (char*)XML_ErrorString(name)) MYCONST(XML_ERROR_NO_MEMORY); MYCONST(XML_ERROR_SYNTAX); MYCONST(XML_ERROR_NO_ELEMENTS); MYCONST(XML_ERROR_INVALID_TOKEN); MYCONST(XML_ERROR_UNCLOSED_TOKEN); MYCONST(XML_ERROR_PARTIAL_CHAR); MYCONST(XML_ERROR_TAG_MISMATCH); MYCONST(XML_ERROR_DUPLICATE_ATTRIBUTE); MYCONST(XML_ERROR_JUNK_AFTER_DOC_ELEMENT); MYCONST(XML_ERROR_PARAM_ENTITY_REF); MYCONST(XML_ERROR_UNDEFINED_ENTITY); MYCONST(XML_ERROR_RECURSIVE_ENTITY_REF); MYCONST(XML_ERROR_ASYNC_ENTITY); MYCONST(XML_ERROR_BAD_CHAR_REF); MYCONST(XML_ERROR_BINARY_ENTITY_REF); MYCONST(XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF); MYCONST(XML_ERROR_MISPLACED_XML_PI); MYCONST(XML_ERROR_UNKNOWN_ENCODING); MYCONST(XML_ERROR_INCORRECT_ENCODING); MYCONST(XML_ERROR_UNCLOSED_CDATA_SECTION); MYCONST(XML_ERROR_EXTERNAL_ENTITY_HANDLING); MYCONST(XML_ERROR_NOT_STANDALONE); MYCONST(XML_ERROR_UNEXPECTED_STATE); MYCONST(XML_ERROR_ENTITY_DECLARED_IN_PE); MYCONST(XML_ERROR_FEATURE_REQUIRES_XML_DTD); MYCONST(XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING); /* Added in Expat 1.95.7. */ MYCONST(XML_ERROR_UNBOUND_PREFIX); /* Added in Expat 1.95.8. */ MYCONST(XML_ERROR_UNDECLARING_PREFIX); MYCONST(XML_ERROR_INCOMPLETE_PE); MYCONST(XML_ERROR_XML_DECL); MYCONST(XML_ERROR_TEXT_DECL); MYCONST(XML_ERROR_PUBLICID); MYCONST(XML_ERROR_SUSPENDED); MYCONST(XML_ERROR_NOT_SUSPENDED); MYCONST(XML_ERROR_ABORTED); MYCONST(XML_ERROR_FINISHED); MYCONST(XML_ERROR_SUSPEND_PE); PyModule_AddStringConstant(errors_module, "__doc__", "Constants used to describe error conditions."); #undef MYCONST #define MYCONST(c) PyModule_AddIntConstant(m, #c, c) MYCONST(XML_PARAM_ENTITY_PARSING_NEVER); MYCONST(XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE); MYCONST(XML_PARAM_ENTITY_PARSING_ALWAYS); #undef MYCONST #define MYCONST(c) PyModule_AddIntConstant(model_module, #c, c) PyModule_AddStringConstant(model_module, "__doc__", "Constants used to interpret content model information."); MYCONST(XML_CTYPE_EMPTY); MYCONST(XML_CTYPE_ANY); MYCONST(XML_CTYPE_MIXED); MYCONST(XML_CTYPE_NAME); MYCONST(XML_CTYPE_CHOICE); MYCONST(XML_CTYPE_SEQ); MYCONST(XML_CQUANT_NONE); MYCONST(XML_CQUANT_OPT); MYCONST(XML_CQUANT_REP); MYCONST(XML_CQUANT_PLUS); #undef MYCONST /* initialize pyexpat dispatch table */ capi.size = sizeof(capi); capi.magic = PyExpat_CAPI_MAGIC; capi.MAJOR_VERSION = XML_MAJOR_VERSION; capi.MINOR_VERSION = XML_MINOR_VERSION; capi.MICRO_VERSION = XML_MICRO_VERSION; capi.ErrorString = XML_ErrorString; capi.GetErrorCode = XML_GetErrorCode; capi.GetErrorColumnNumber = XML_GetErrorColumnNumber; capi.GetErrorLineNumber = XML_GetErrorLineNumber; capi.Parse = XML_Parse; capi.ParserCreate_MM = XML_ParserCreate_MM; capi.ParserFree = XML_ParserFree; capi.SetCharacterDataHandler = XML_SetCharacterDataHandler; capi.SetCommentHandler = XML_SetCommentHandler; capi.SetDefaultHandlerExpand = XML_SetDefaultHandlerExpand; capi.SetElementHandler = XML_SetElementHandler; capi.SetNamespaceDeclHandler = XML_SetNamespaceDeclHandler; capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler; capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler; capi.SetUserData = XML_SetUserData; /* export using capsule */ capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL); if (capi_object) PyModule_AddObject(m, "expat_CAPI", capi_object); return m; } static void clear_handlers(xmlparseobject *self, int initial) { int i = 0; PyObject *temp; for (; handler_info[i].name != NULL; i++) { if (initial) self->handlers[i] = NULL; else { temp = self->handlers[i]; self->handlers[i] = NULL; Py_XDECREF(temp); handler_info[i].setter(self->itself, NULL); } } } static struct HandlerInfo handler_info[] = { {"StartElementHandler", (xmlhandlersetter)XML_SetStartElementHandler, (xmlhandler)my_StartElementHandler}, {"EndElementHandler", (xmlhandlersetter)XML_SetEndElementHandler, (xmlhandler)my_EndElementHandler}, {"ProcessingInstructionHandler", (xmlhandlersetter)XML_SetProcessingInstructionHandler, (xmlhandler)my_ProcessingInstructionHandler}, {"CharacterDataHandler", (xmlhandlersetter)XML_SetCharacterDataHandler, (xmlhandler)my_CharacterDataHandler}, {"UnparsedEntityDeclHandler", (xmlhandlersetter)XML_SetUnparsedEntityDeclHandler, (xmlhandler)my_UnparsedEntityDeclHandler}, {"NotationDeclHandler", (xmlhandlersetter)XML_SetNotationDeclHandler, (xmlhandler)my_NotationDeclHandler}, {"StartNamespaceDeclHandler", (xmlhandlersetter)XML_SetStartNamespaceDeclHandler, (xmlhandler)my_StartNamespaceDeclHandler}, {"EndNamespaceDeclHandler", (xmlhandlersetter)XML_SetEndNamespaceDeclHandler, (xmlhandler)my_EndNamespaceDeclHandler}, {"CommentHandler", (xmlhandlersetter)XML_SetCommentHandler, (xmlhandler)my_CommentHandler}, {"StartCdataSectionHandler", (xmlhandlersetter)XML_SetStartCdataSectionHandler, (xmlhandler)my_StartCdataSectionHandler}, {"EndCdataSectionHandler", (xmlhandlersetter)XML_SetEndCdataSectionHandler, (xmlhandler)my_EndCdataSectionHandler}, {"DefaultHandler", (xmlhandlersetter)XML_SetDefaultHandler, (xmlhandler)my_DefaultHandler}, {"DefaultHandlerExpand", (xmlhandlersetter)XML_SetDefaultHandlerExpand, (xmlhandler)my_DefaultHandlerExpandHandler}, {"NotStandaloneHandler", (xmlhandlersetter)XML_SetNotStandaloneHandler, (xmlhandler)my_NotStandaloneHandler}, {"ExternalEntityRefHandler", (xmlhandlersetter)XML_SetExternalEntityRefHandler, (xmlhandler)my_ExternalEntityRefHandler}, {"StartDoctypeDeclHandler", (xmlhandlersetter)XML_SetStartDoctypeDeclHandler, (xmlhandler)my_StartDoctypeDeclHandler}, {"EndDoctypeDeclHandler", (xmlhandlersetter)XML_SetEndDoctypeDeclHandler, (xmlhandler)my_EndDoctypeDeclHandler}, {"EntityDeclHandler", (xmlhandlersetter)XML_SetEntityDeclHandler, (xmlhandler)my_EntityDeclHandler}, {"XmlDeclHandler", (xmlhandlersetter)XML_SetXmlDeclHandler, (xmlhandler)my_XmlDeclHandler}, {"ElementDeclHandler", (xmlhandlersetter)XML_SetElementDeclHandler, (xmlhandler)my_ElementDeclHandler}, {"AttlistDeclHandler", (xmlhandlersetter)XML_SetAttlistDeclHandler, (xmlhandler)my_AttlistDeclHandler}, #if XML_COMBINED_VERSION >= 19504 {"SkippedEntityHandler", (xmlhandlersetter)XML_SetSkippedEntityHandler, (xmlhandler)my_SkippedEntityHandler}, #endif {NULL, NULL, NULL} /* sentinel */ }; #n1660'>1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcleanlooksstyle.h"
#include "qcleanlooksstyle_p.h"

#if !defined(QT_NO_STYLE_CLEANLOOKS) || defined(QT_PLUGIN)

#include "qwindowsstyle_p.h"
#include <qcombobox.h>
#include <qpushbutton.h>
#include <qpainter.h>
#include <qdir.h>
#include <qhash.h>
#include <qstyleoption.h>
#include <qapplication.h>
#include <qmainwindow.h>
#include <qfont.h>
#include <qgroupbox.h>
#include <qprocess.h>
#include <qpixmapcache.h>
#include <qdialogbuttonbox.h>
#include <qscrollbar.h>
#include <qspinbox.h>
#include <qslider.h>
#include <qsplitter.h>
#include <qprogressbar.h>
#include <qtoolbar.h>
#include <qwizard.h>
#include <qlibrary.h>
#include <private/qstylehelper_p.h>

QT_BEGIN_NAMESPACE

using namespace QStyleHelper;

enum Direction {
    TopDown,
    FromLeft,
    BottomUp,
    FromRight
};

// from windows style
static const int windowsItemFrame        =  2; // menu item frame width
static const int windowsItemHMargin      =  3; // menu item hor text margin
static const int windowsItemVMargin      =  8; // menu item ver text margin
static const int windowsRightBorder      = 15; // right border on windows

/* XPM */
static const char * const dock_widget_close_xpm[] = {
    "11 13 7 1",
    " 	c None",
    ".	c #D5CFCB",
    "+	c #8F8B88",
    "@	c #6C6A67",
    "#	c #ABA6A3",
    "$	c #B5B0AC",
    "%	c #A4A09D",
    "           ",
    " +@@@@@@@+ ",
    "+#       #+",
    "@ $@   @$ @",
    "@ @@@ @@@ @",
    "@  @@@@@  @",
    "@   @@@   @",
    "@  @@@@@  @",
    "@ @@@ @@@ @",
    "@ $@   @$ @",
    "+%       #+",
    " +@@@@@@@+ ",
    "           "};

static const char * const qt_cleanlooks_arrow_down_xpm[] = {
    "11 7 2 1",
    " 	c None",
    "x	c #000000",
    "           ",
    "  x     x  ",
    " xxx   xxx ",
    "  xxxxxxx  ",
    "   xxxxx   ",
    "    xxx    ",
    "     x     "};

static const char * const qt_cleanlooks_arrow_up_xpm[] = {
    "11 7 2 1",
    " 	c None",
    "x	c #000000",
    "     x     ",
    "    xxx    ",
    "   xxxxx   ",
    "  xxxxxxx  ",
    " xxx   xxx ",
    "  x     x  ",
    "           "};

static const char * const dock_widget_restore_xpm[] = {
    "11 13 7 1",
    " 	c None",
    ".	c #D5CFCB",
    "+	c #8F8B88",
    "@	c #6C6A67",
    "#	c #ABA6A3",
    "$	c #B5B0AC",
    "%	c #A4A09D",
    "           ",
    " +@@@@@@@+ ",
    "+#       #+",
    "@   #@@@# @",
    "@   @   @ @",
    "@ #@@@# @ @",
    "@ @   @ @ @",
    "@ @   @@@ @",
    "@ @   @   @",
    "@ #@@@#   @",
    "+%       #+",
    " +@@@@@@@+ ",
    "           "};

static const char * const workspace_minimize[] = {
    "11 13 7 1",
    " 	c None",
    ".	c #D5CFCB",
    "+	c #8F8B88",
    "@	c #6C6A67",
    "#	c #ABA6A3",
    "$	c #B5B0AC",
    "%	c #A4A09D",
    "           ",
    " +@@@@@@@+ ",
    "+#       #+",
    "@         @",
    "@         @",
    "@         @",
    "@ @@@@@@@ @",
    "@ @@@@@@@ @",
    "@         @",
    "@         @",
    "+%       #+",
    " +@@@@@@@+ ",
    "           "};


static const char * const qt_titlebar_context_help[] = {
    "10 10 3 1",
    "  c None",
    "# c #000000",
    "+ c #444444",
    "  +####+  ",
    " ###  ### ",
    " ##    ## ",
    "     +##+ ",
    "    +##   ",
    "    ##    ",
    "    ##    ",
    "          ",
    "    ##    ",
    "    ##    "};

static const char * const qt_cleanlooks_radiobutton[] = {
    "13 13 9 1",
    " 	c None",
    ".	c #ABA094",
    "+	c #B7ADA0",
    "@	c #C4BBB2",
    "#	c #DDD4CD",
    "$	c #E7E1E0",
    "%	c #F4EFED",
    "&	c #FFFAF9",
    "*	c #FCFEFB",
    "   #@...@#   ",
    "  @+@#$$#+@  ",
    " @+$%%***&@@ ",
    "#+$%**&&**&+#",
    "@@$&&******#@",
    ".#**********.",
    ".$&******&*&.",
    ".$*&******&*.",
    "+#********&#@",
    "#+*********+#",
    " @@*******@@ ",
    "  @+#%*%#+@  ",
    "   #@...+#   "};

static const char * const qt_cleanlooks_radiobutton_checked[] = {
    "13 13 20 1",
    " 	c None",
    ".	c #A8ABAE",
    "+	c #596066",
    "@	c #283138",
    "#	c #A9ACAF",
    "$	c #A6A9AB",
    "%	c #6B7378",
    "&	c #8C9296",
    "*	c #A2A6AA",
    "=	c #61696F",
    "-	c #596065",
    ";	c #93989C",
    ">	c #777E83",
    ",	c #60686E",
    "'	c #252D33",
    ")	c #535B62",
    "!	c #21292E",
    "~	c #242B31",
    "{	c #1F262B",
    "]	c #41484E",
    "             ",
    "             ",
    "             ",
    "    .+@+#    ",
    "   $%&*&=#   ",
    "   -&;>,'+   ",
    "   @*>,)!@   ",
    "   +&,)~{+   ",
    "   #='!{]#   ",
    "    #+@+#    ",
    "             ",
    "             ",
    "             "};


static const char * const qt_scrollbar_button_arrow_left[] = {
    "4 7 2 1",
    "   c None",
    "*  c #BFBFBF",
    "   *",
    "  **",
    " ***",
    "****",
    " ***",
    "  **",
    "   *"};

static const char * const qt_scrollbar_button_arrow_right[] = {
    "4 7 2 1",
    "   c None",
    "*  c #BFBFBF",
    "*   ",
    "**  ",
    "*** ",
    "****",
    "*** ",
    "**  ",
    "*   "};

static const char * const qt_scrollbar_button_arrow_up[] = {
    "7 4 2 1",
    "   c None",
    "*  c #BFBFBF",
    "   *   ",
    "  ***  ",
    " ***** ",
    "*******"};

static const char * const qt_scrollbar_button_arrow_down[] = {
    "7 4 2 1",
    "   c None",
    "*  c #BFBFBF",
    "*******",
    " ***** ",
    "  ***  ",
    "   *   "};

static const char * const qt_spinbox_button_arrow_down[] = {
    "7 4 2 1",
    "   c None",
    "*  c #BFBFBF",
    "*******",
    " ***** ",
    "  ***  ",
    "   *   "};

static const char * const qt_spinbox_button_arrow_up[] = {
    "7 4 2 1",
    "   c None",
    "*  c #BFBFBF",
    "   *   ",
    "  ***  ",
    " ***** ",
    "*******"};

static const char * const qt_scrollbar_button_left[] = {
    "16 16 6 1",
    "   c None",
    ".  c #BFBFBF",
    "+  c #979797",
    "#  c #FAFAFA",
    "<  c #FAFAFA",
    "*  c #FAFAFA",
    " .++++++++++++++",
    ".+#############+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    ".+<<<<<<<<<<<<<+",
    " .++++++++++++++"};

static const char * const qt_scrollbar_button_right[] = {
    "16 16 6 1",
    "   c None",
    ".  c #BFBFBF",
    "+  c #979797",
    "#  c #FAFAFA",
    "<  c #FAFAFA",
    "*  c #FAFAFA",
    "++++++++++++++. ",
    "+#############+.",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+<<<<<<<<<<<<<+.",
    "++++++++++++++. "};

static const char * const qt_scrollbar_button_up[] = {
    "16 16 6 1",
    "   c None",
    ".  c #BFBFBF",
    "+  c #979797",
    "#  c #FAFAFA",
    "<  c #FAFAFA",
    "*  c #FAFAFA",
    " .++++++++++++. ",
    ".+############+.",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+<<<<<<<<<<<<<<+",
    "++++++++++++++++"};

static const char * const qt_scrollbar_button_down[] = {
    "16 16 6 1",
    "   c None",
    ".  c #BFBFBF",
    "+  c #979797",
    "#  c #FAFAFA",
    "<  c #FAFAFA",
    "*  c #FAFAFA",
    "++++++++++++++++",
    "+##############+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    "+#            <+",
    ".+<<<<<<<<<<<<+.",
    " .++++++++++++. "};

static const char * const qt_cleanlooks_menuitem_checkbox_checked[] = {
    "8 7 6 1",
    " 	g None",
    ".	g #959595",
    "+	g #676767",
    "@	g #454545",
    "#	g #1D1D1D",
    "0	g #101010",
    "      ..",
    "     .+ ",
    "    .+  ",
    "0  .@   ",
    "@#++.   ",
    "  @#    ",
    "   .    "};

static const char * const qt_cleanlooks_checkbox_checked[] = {
    "13 13 3 1",
    " 	c None",
    ".	c #272D33",
    "%	c #666666",

    "             ",
    "          %  ",
    "         %.  ",
    "        %.%  ",
    "       %..   ",
    "  %.% %..    ",
    "  %..%..%    ",
    "   %...%     ",
    "    %..%     ",
    "     %.%     ",
    "      %      ",
    "             ",
    "             "};

static void qt_cleanlooks_draw_gradient(QPainter *painter, const QRect &rect, const QColor &gradientStart,
                                        const QColor &gradientStop, Direction direction = TopDown, QBrush bgBrush = QBrush())
{
        int x = rect.center().x();
        int y = rect.center().y();
        QLinearGradient *gradient;
        switch(direction) {
            case FromLeft:
                gradient = new QLinearGradient(rect.left(), y, rect.right(), y);
                break;
            case FromRight:
                gradient = new QLinearGradient(rect.right(), y, rect.left(), y);
                break;
            case BottomUp:
                gradient = new QLinearGradient(x, rect.bottom(), x, rect.top());
                break;
            case TopDown:
            default:
                gradient = new QLinearGradient(x, rect.top(), x, rect.bottom());
                break;
        }
        if (bgBrush.gradient())
            gradient->setStops(bgBrush.gradient()->stops());
        else {
            gradient->setColorAt(0, gradientStart);
            gradient->setColorAt(1, gradientStop);
        }
        painter->fillRect(rect, *gradient);
        delete gradient;
}

static void qt_cleanlooks_draw_buttongradient(QPainter *painter, const QRect &rect, const QColor &gradientStart,
                                                const QColor &gradientMid, const QColor &gradientStop, Direction direction = TopDown,
                                                QBrush bgBrush = QBrush())
{
        int x = rect.center().x();
        int y = rect.center().y();
        QLinearGradient *gradient;
        bool horizontal = false;
        switch(direction) {
            case FromLeft:
                horizontal = true;
                gradient = new QLinearGradient(rect.left(), y, rect.right(), y);
                break;
            case FromRight:
                horizontal = true;
                gradient = new QLinearGradient(rect.right(), y, rect.left(), y);
                break;
            case BottomUp:
                gradient = new QLinearGradient(x, rect.bottom(), x, rect.top());
                break;
            case TopDown:
            default:
                gradient = new QLinearGradient(x, rect.top(), x, rect.bottom());
                break;
        }
        if (bgBrush.gradient())
            gradient->setStops(bgBrush.gradient()->stops());
        else {
            int size = horizontal ? rect.width() : rect.height() ;
            if (size > 4) {
                float edge = 4.0/(float)size;
                gradient->setColorAt(0, gradientStart);
                gradient->setColorAt(edge, gradientMid.lighter(104));
                gradient->setColorAt(1.0 - edge, gradientMid.darker(100));
                gradient->setColorAt(1.0, gradientStop);
            }
        }
        painter->fillRect(rect, *gradient);
        delete gradient;
}

static void qt_cleanlooks_draw_mdibutton(QPainter *painter, const QStyleOptionTitleBar *option, const QRect &tmp, bool hover, bool sunken)
{
    QColor dark;
    dark.setHsv(option->palette.button().color().hue(),
                qMin(255, (int)(option->palette.button().color().saturation()*1.9)),
                qMin(255, (int)(option->palette.button().color().value()*0.7)));

    QColor highlight = option->palette.highlight().color();

    bool active = (option->titleBarState & QStyle::State_Active);
    QColor titleBarHighlight(255, 255, 255, 60);

    if (sunken)
        painter->fillRect(tmp.adjusted(1, 1, -1, -1), option->palette.highlight().color().darker(120));
    else if (hover)
        painter->fillRect(tmp.adjusted(1, 1, -1, -1), QColor(255, 255, 255, 20));

    QColor mdiButtonGradientStartColor;
    QColor mdiButtonGradientStopColor;

    mdiButtonGradientStartColor = QColor(0, 0, 0, 40);
    mdiButtonGradientStopColor = QColor(255, 255, 255, 60);

    if (sunken)
        titleBarHighlight = highlight.darker(130);

    QLinearGradient gradient(tmp.center().x(), tmp.top(), tmp.center().x(), tmp.bottom());
    gradient.setColorAt(0, mdiButtonGradientStartColor);
    gradient.setColorAt(1, mdiButtonGradientStopColor);
    QColor mdiButtonBorderColor(active ? option->palette.highlight().color().darker(180): dark.darker(110));

    painter->setPen(QPen(mdiButtonBorderColor, 1));
    const QLine lines[4] = {
        QLine(tmp.left() + 2, tmp.top(), tmp.right() - 2, tmp.top()),
        QLine(tmp.left() + 2, tmp.bottom(), tmp.right() - 2, tmp.bottom()),
        QLine(tmp.left(), tmp.top() + 2, tmp.left(), tmp.bottom() - 2),
        QLine(tmp.right(), tmp.top() + 2, tmp.right(), tmp.bottom() - 2)
    };
    painter->drawLines(lines, 4);
    const QPoint points[4] = {
        QPoint(tmp.left() + 1, tmp.top() + 1),
        QPoint(tmp.right() - 1, tmp.top() + 1),
        QPoint(tmp.left() + 1, tmp.bottom() - 1),
        QPoint(tmp.right() - 1, tmp.bottom() - 1)
    };
    painter->drawPoints(points, 4);

    painter->setPen(titleBarHighlight);
    painter->drawLine(tmp.left() + 2, tmp.top() + 1, tmp.right() - 2, tmp.top() + 1);
    painter->drawLine(tmp.left() + 1, tmp.top() + 2, tmp.left() + 1, tmp.bottom() - 2);

    painter->setPen(QPen(gradient, 1));
    painter->drawLine(tmp.right() + 1, tmp.top() + 2, tmp.right() + 1, tmp.bottom() - 2);
    painter->drawPoint(tmp.right() , tmp.top() + 1);

    painter->drawLine(tmp.left() + 2, tmp.bottom() + 1, tmp.right() - 2, tmp.bottom() + 1);
    painter->drawPoint(tmp.left() + 1, tmp.bottom());
    painter->drawPoint(tmp.right() - 1, tmp.bottom());
    painter->drawPoint(tmp.right() , tmp.bottom() - 1);
}

/*!
    \class QCleanlooksStyle
    \brief The QCleanlooksStyle class provides a widget style similar to the
    Clearlooks style available in GNOME.
    \since 4.2

    The Cleanlooks style provides a look and feel for widgets
    that closely resembles the Clearlooks style, introduced by Richard
    Stellingwerff and Daniel Borgmann.

    \sa {Cleanlooks Style Widget Gallery}, QWindowsXPStyle, QMacStyle, QWindowsStyle,
        QCDEStyle, QMotifStyle, QPlastiqueStyle
*/

/*!
    Constructs a QCleanlooksStyle object.
*/
QCleanlooksStyle::QCleanlooksStyle() : QWindowsStyle(*new QCleanlooksStylePrivate)
{
    setObjectName(QLatin1String("CleanLooks"));
}

/*!
    \internal

    Constructs a QCleanlooksStyle object.
*/
QCleanlooksStyle::QCleanlooksStyle(QCleanlooksStylePrivate &dd) : QWindowsStyle(dd)
{
}

/*!
    Destroys the QCleanlooksStyle object.
*/
QCleanlooksStyle::~QCleanlooksStyle()
{
}

/*!
    \fn void QCleanlooksStyle::drawItemText(QPainter *painter, const QRect &rectangle, int alignment, const QPalette &palette,
                                    bool enabled, const QString& text, QPalette::ColorRole textRole) const

    Draws the given \a text in the specified \a rectangle using the
    provided \a painter and \a palette.

    Text is drawn using the painter's pen. If an explicit \a textRole
    is specified, then the text is drawn using the \a palette's color
    for the specified role.  The \a enabled value indicates whether or
    not the item is enabled; when reimplementing, this value should
    influence how the item is drawn.

    The text is aligned and wrapped according to the specified \a
    alignment.

    \sa Qt::Alignment
*/
void QCleanlooksStyle::drawItemText(QPainter *painter, const QRect &rect, int alignment, const QPalette &pal,
                                    bool enabled, const QString& text, QPalette::ColorRole textRole) const
{
    if (text.isEmpty())
        return;

    QPen savedPen = painter->pen();
    if (textRole != QPalette::NoRole) {
        painter->setPen(QPen(pal.brush(textRole), savedPen.widthF()));
    }
    if (!enabled) {
        QPen pen = painter->pen();
        painter->setPen(pen);
    }
    painter->drawText(rect, alignment, text);
    painter->setPen(savedPen);
}

static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50)
{
    const int maxFactor = 100;
    QColor tmp = colorA;
    tmp.setRed((tmp.red() * factor) / maxFactor + (colorB.red() * (maxFactor - factor)) / maxFactor);
    tmp.setGreen((tmp.green() * factor) / maxFactor + (colorB.green() * (maxFactor - factor)) / maxFactor);
    tmp.setBlue((tmp.blue() * factor) / maxFactor + (colorB.blue() * (maxFactor - factor)) / maxFactor);
    return tmp;
}

/*!
    \reimp
*/
void QCleanlooksStyle::drawPrimitive(PrimitiveElement elem,
                        const QStyleOption *option,
                        QPainter *painter, const QWidget *widget) const
{
    Q_ASSERT(option);
    QRect rect = option->rect;
    int state = option->state;
    QColor button = option->palette.button().color();
    QColor buttonShadow = option->palette.button().color().darker(110);
    QColor buttonShadowAlpha = buttonShadow;
    buttonShadowAlpha.setAlpha(128);
    QColor darkOutline;
    QColor dark;
    darkOutline.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*3.0)),
                qMin(255, (int)(button.value()*0.6)));
    dark.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*1.9)),
                qMin(255, (int)(button.value()*0.7)));
    QColor tabFrameColor = mergedColors(option->palette.background().color(),
                                                dark.lighter(135), 60);

    switch(elem) {
#ifndef QT_NO_TABBAR
    case PE_FrameTabBarBase:
        if (const QStyleOptionTabBarBase *tbb
                = qstyleoption_cast<const QStyleOptionTabBarBase *>(option)) {
            painter->save();
            painter->setPen(QPen(darkOutline.lighter(110), 0));
            switch (tbb->shape) {
            case QTabBar::RoundedNorth: {
                QRegion region(tbb->rect);
                region -= tbb->selectedTabRect;
                painter->drawLine(tbb->rect.topLeft(), tbb->rect.topRight());
                painter->setClipRegion(region);
                painter->setPen(option->palette.light().color());
                painter->drawLine(tbb->rect.topLeft() + QPoint(0, 1),
                                  tbb->rect.topRight()  + QPoint(0, 1));
            }
                break;
            case QTabBar::RoundedWest:
                painter->drawLine(tbb->rect.left(), tbb->rect.top(), tbb->rect.left(), tbb->rect.bottom());
                break;
            case QTabBar::RoundedSouth:
                painter->drawLine(tbb->rect.left(), tbb->rect.bottom(),
                            tbb->rect.right(), tbb->rect.bottom());
                break;
            case QTabBar::RoundedEast:
                painter->drawLine(tbb->rect.topRight(), tbb->rect.bottomRight());
                break;
            case QTabBar::TriangularNorth:
            case QTabBar::TriangularEast:
            case QTabBar::TriangularWest:
            case QTabBar::TriangularSouth:
                painter->restore();
                QWindowsStyle::drawPrimitive(elem, option, painter, widget);
                return;
            }
            painter->restore();
        }
        return;
#endif // QT_NO_TABBAR
    case PE_IndicatorViewItemCheck:
        {
            QStyleOptionButton button;
            button.QStyleOption::operator=(*option);
            button.state &= ~State_MouseOver;
            proxy()->drawPrimitive(PE_IndicatorCheckBox, &button, painter, widget);
        }
        return;
    case PE_IndicatorHeaderArrow:
        if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
            QRect r = header->rect;
            QImage arrow;
            if (header->sortIndicator & QStyleOptionHeader::SortUp)
                arrow = QImage(qt_cleanlooks_arrow_up_xpm);
            else if (header->sortIndicator & QStyleOptionHeader::SortDown)
                arrow = QImage(qt_cleanlooks_arrow_down_xpm);
            if (!arrow.isNull()) {
                r.setSize(arrow.size());
                r.moveCenter(header->rect.center());
                arrow.setColor(1, header->palette.foreground().color().rgba());
                painter->drawImage(r, arrow);
            }
        }
        break;
    case PE_IndicatorButtonDropDown:
        proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
        break;
    case PE_IndicatorToolBarSeparator:
        {
            QRect rect = option->rect;
            const int margin = 6;
            if (option->state & State_Horizontal) {
                const int offset = rect.width()/2;
                painter->setPen(QPen(option->palette.background().color().darker(110)));
                painter->drawLine(rect.bottomLeft().x() + offset,
                            rect.bottomLeft().y() - margin,
                            rect.topLeft().x() + offset,
                            rect.topLeft().y() + margin);
                painter->setPen(QPen(option->palette.background().color().lighter(110)));
                painter->drawLine(rect.bottomLeft().x() + offset + 1,
                            rect.bottomLeft().y() - margin,
                            rect.topLeft().x() + offset + 1,
                            rect.topLeft().y() + margin);
            } else { //Draw vertical separator
                const int offset = rect.height()/2;
                painter->setPen(QPen(option->palette.background().color().darker(110)));
                painter->drawLine(rect.topLeft().x() + margin ,
                            rect.topLeft().y() + offset,
                            rect.topRight().x() - margin,
                            rect.topRight().y() + offset);
                painter->setPen(QPen(option->palette.background().color().lighter(110)));
                painter->drawLine(rect.topLeft().x() + margin ,
                            rect.topLeft().y() + offset + 1,
                            rect.topRight().x() - margin,
                            rect.topRight().y() + offset + 1);
            }
        }
        break;
    case PE_Frame:
        painter->save();
        painter->setPen(dark.lighter(108));
        painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
        painter->restore();
        break;
    case PE_FrameMenu:
        painter->save();
        {
            painter->setPen(QPen(darkOutline, 1));
            painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
            QColor frameLight = option->palette.background().color().lighter(160);
            QColor frameShadow = option->palette.background().color().darker(110);

            //paint beveleffect
            QRect frame = option->rect.adjusted(1, 1, -1, -1);
            painter->setPen(frameLight);
            painter->drawLine(frame.topLeft(), frame.bottomLeft());
            painter->drawLine(frame.topLeft(), frame.topRight());

            painter->setPen(frameShadow);
            painter->drawLine(frame.topRight(), frame.bottomRight());
            painter->drawLine(frame.bottomLeft(), frame.bottomRight());
        }
        painter->restore();
        break;
    case PE_FrameDockWidget:

        painter->save();
        {
            QColor softshadow = option->palette.background().color().darker(120);

            QRect rect= option->rect;
            painter->setPen(softshadow);
            painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
            painter->setPen(QPen(option->palette.light(), 0));
            painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1), QPoint(rect.left() + 1, rect.bottom() - 1));
            painter->setPen(QPen(option->palette.background().color().darker(120), 0));
            painter->drawLine(QPoint(rect.left() + 1, rect.bottom() - 1), QPoint(rect.right() - 2, rect.bottom() - 1));
            painter->drawLine(QPoint(rect.right() - 1, rect.top() + 1), QPoint(rect.right() - 1, rect.bottom() - 1));

        }
        painter->restore();
        break;
    case PE_PanelButtonTool:
        painter->save();
        if ((option->state & State_Enabled || option->state & State_On) || !(option->state & State_AutoRaise)) {
            QPen oldPen = painter->pen();

            if (widget && widget->inherits("QDockWidgetTitleButton")) {
                   if (option->state & State_MouseOver)
                       proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
            } else {
                proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
            }
        }
        painter->restore();
        break;
    case PE_IndicatorDockWidgetResizeHandle:
        {
            QStyleOption dockWidgetHandle = *option;
            bool horizontal = option->state & State_Horizontal;
            if (horizontal)
                dockWidgetHandle.state &= ~State_Horizontal;
            else
                dockWidgetHandle.state |= State_Horizontal;
            proxy()->drawControl(CE_Splitter, &dockWidgetHandle, painter, widget);
        }
        break;
    case PE_FrameWindow:
        painter->save();
        {
            QRect rect= option->rect;
            painter->setPen(QPen(dark.darker(150), 0));
            painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
            painter->setPen(QPen(option->palette.light(), 0));
            painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1),
                              QPoint(rect.left() + 1, rect.bottom() - 1));
            painter->setPen(QPen(option->palette.background().color().darker(120), 0));
            painter->drawLine(QPoint(rect.left() + 1, rect.bottom() - 1),
                              QPoint(rect.right() - 2, rect.bottom() - 1));
            painter->drawLine(QPoint(rect.right() - 1, rect.top() + 1),
                              QPoint(rect.right() - 1, rect.bottom() - 1));
        }
        painter->restore();
        break;
#ifndef QT_NO_LINEEDIT
    case PE_FrameLineEdit:
        // fall through
#endif // QT_NO_LINEEDIT
#ifdef QT3_SUPPORT
        if (widget && widget->inherits("Q3ToolBar")) {
            proxy()->drawPrimitive(PE_Q3Separator, option, painter, widget);
            break;
        }
#endif
        {
            QPen oldPen = painter->pen();
            if (option->state & State_Enabled) {
                painter->setPen(QPen(option->palette.background(), 0));
                painter->drawRect(rect.adjusted(0, 0, 0, 0));
                painter->drawRect(rect.adjusted(1, 1, -1, -1));
            } else {
                painter->fillRect(rect, option->palette.background());
            }
            QRect r = rect.adjusted(0, 1, 0, -1);
            painter->setPen(buttonShadowAlpha);
            painter->drawLine(QPoint(r.left() + 2, r.top() - 1), QPoint(r.right() - 2, r.top() - 1));
            const QPoint points[8] = {
                QPoint(r.right() - 1, r.top()),
                QPoint(r.right(), r.top() + 1),
                QPoint(r.right() - 1, r.bottom()),
                QPoint(r.right(), r.bottom() - 1),
                QPoint(r.left() + 1, r.top() ),
                QPoint(r.left(), r.top() + 1),
                QPoint(r.left() + 1, r.bottom() ),
                QPoint(r.left(), r.bottom() - 1)
            };
            painter->drawPoints(points, 8);
            painter->setPen(QPen(option->palette.background().color(), 1));
            painter->drawLine(QPoint(r.left() + 2, r.top() + 1), QPoint(r.right() - 2, r.top() + 1));

            if (option->state & State_HasFocus) {
                QColor darkoutline = option->palette.highlight().color().darker(150);
                QColor innerline = mergedColors(option->palette.highlight().color(), Qt::white);
                painter->setPen(QPen(innerline, 0));
                painter->drawRect(rect.adjusted(1, 2, -2, -3));
                painter->setPen(QPen(darkoutline, 0));
            }
            else {
                QColor highlight = Qt::white;
                highlight.setAlpha(130);
                painter->setPen(option->palette.base().color().darker(120));
                painter->drawLine(QPoint(r.left() + 1, r.top() + 1),
                                  QPoint(r.right() - 1, r.top() + 1));
                painter->drawLine(QPoint(r.left() + 1, r.top() + 1),
                                  QPoint(r.left() + 1, r.bottom() - 1));
                painter->setPen(option->palette.base().color());
                painter->drawLine(QPoint(r.right() - 1, r.top() + 1),
                                  QPoint(r.right() - 1, r.bottom() - 1));
                painter->setPen(highlight);
                painter->drawLine(QPoint(r.left() + 1, r.bottom() + 1),
                                  QPoint(r.right() - 1, r.bottom() + 1));
                painter->drawPoint(QPoint(r.left(), r.bottom()));
                painter->drawPoint(QPoint(r.right(), r.bottom() ));
                painter->setPen(QPen(darkOutline.lighter(115), 1));
            }
            painter->drawLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2));
            painter->drawLine(QPoint(r.right(), r.top() + 2), QPoint(r.right(), r.bottom() - 2));
            painter->drawLine(QPoint(r.left() + 2, r.bottom()), QPoint(r.right() - 2, r.bottom()));
            const QPoint points2[4] = {
                QPoint(r.right() - 1, r.bottom() - 1),
                QPoint(r.right() - 1, r.top() + 1),
                QPoint(r.left() + 1, r.bottom() - 1),
                QPoint(r.left() + 1, r.top() + 1)
            };
            painter->drawPoints(points2, 4);
            painter->drawLine(QPoint(r.left() + 2, r.top()), QPoint(r.right() - 2, r.top()));
            painter->setPen(oldPen);
        }
        break;
    case PE_IndicatorCheckBox:
        painter->save();
        if (const QStyleOptionButton *checkbox = qstyleoption_cast<const QStyleOptionButton*>(option)) {
            QRect checkRect;
            checkRect.setX(rect.left() );
            checkRect.setY(rect.top() );
            checkRect.setWidth(rect.width() - 1);
            checkRect.setHeight(rect.height() - 1);
            if (state & State_Sunken)
                painter->setBrush(dark.lighter(130));
            else
                painter->setBrush(option->palette.base());
            painter->setPen(QPen(dark.lighter(110), 0));
            painter->drawRect(checkRect);
            if (checkbox->state & (State_On | State_Sunken  | State_NoChange)) {
                QImage image(qt_cleanlooks_checkbox_checked);
                QColor fillColor = option->palette.text().color();
                image.setColor(1, fillColor.rgba()); 
                fillColor.setAlpha(100);
                image.setColor(2, fillColor.rgba()); 
                painter->drawImage(rect, image);
                if (checkbox->state & State_NoChange) {
                    QColor bgc = option->palette.background().color();
                    bgc.setAlpha(127);
                    painter->fillRect(checkRect.adjusted(1, 1, -1, -1), bgc);
                }
            }
        }
        painter->restore();
        break;
    case PE_IndicatorRadioButton:
        painter->save();
        {
            painter->setRenderHint(QPainter::SmoothPixmapTransform);
            QRect checkRect = rect.adjusted(0, 0, 0, 0);
            if (state & (State_On )) {
                painter->drawImage(rect, QImage(qt_cleanlooks_radiobutton));
                painter->drawImage(checkRect, QImage(qt_cleanlooks_radiobutton_checked));
            }
            else if (state & State_Sunken) {
                painter->drawImage(rect, QImage(qt_cleanlooks_radiobutton));
                QColor bgc = buttonShadow;
                painter->setRenderHint(QPainter::Antialiasing);
                painter->setBrush(bgc);
                painter->setPen(Qt::NoPen);
                painter->drawEllipse(rect.adjusted(1, 1, -1, -1));                }
            else {
                painter->drawImage(rect, QImage(qt_cleanlooks_radiobutton));
            }
        }
        painter->restore();
    break;
    case PE_IndicatorToolBarHandle:
        painter->save();
        if (option->state & State_Horizontal) {
            for (int i = rect.height()/5; i <= 4*(rect.height()/5) ; ++i) {
                int y = rect.topLeft().y() + i + 1;
                int x1 = rect.topLeft().x() + 3;
                int x2 = rect.topRight().x() - 2;

                if (i % 2 == 0)
                    painter->setPen(QPen(option->palette.light(), 0));
                else
                    painter->setPen(QPen(dark.lighter(110), 0));
                painter->drawLine(x1, y, x2, y);
            }
        }
        else { //vertical toolbar
            for (int i = rect.width()/5; i <= 4*(rect.width()/5) ; ++i) {
                int x = rect.topLeft().x() + i + 1;
                int y1 = rect.topLeft().y() + 3;
                int y2 = rect.topLeft().y() + 5;

                if (i % 2 == 0)
                    painter->setPen(QPen(option->palette.light(), 0));
                else
                    painter->setPen(QPen(dark.lighter(110), 0));
                painter->drawLine(x, y1, x, y2);
            }
        }
        painter->restore();
        break;
    case PE_FrameDefaultButton:
        case PE_FrameFocusRect:
        if (const QStyleOptionFocusRect *focusFrame = qstyleoption_cast<const QStyleOptionFocusRect *>(option)) {
            if (!(focusFrame->state & State_KeyboardFocusChange))
                return;
            QRect rect = focusFrame->rect;
            painter->save();
            painter->setBackgroundMode(Qt::TransparentMode);
            painter->setBrush(QBrush(dark.darker(120), Qt::Dense4Pattern));
            painter->setBrushOrigin(rect.topLeft());
            painter->setPen(Qt::NoPen);
            const QRect rects[4] = {
                QRect(rect.left(), rect.top(), rect.width(), 1),    // Top
                QRect(rect.left(), rect.bottom(), rect.width(), 1), // Bottom
                QRect(rect.left(), rect.top(), 1, rect.height()),   // Left
                QRect(rect.right(), rect.top(), 1, rect.height())   // Right
            };
            painter->drawRects(rects, 4);
            painter->restore();
        }
        break;
    case PE_PanelButtonCommand:
        {
            bool isDefault = false;
            bool isFlat = false;
            bool isDown = (option->state & State_Sunken) || (option->state & State_On);
            QPen oldPen = painter->pen();
            QBrush oldBrush = painter->brush();
            QRect r;

            if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton*>(option)) {
                isDefault = (button->features & QStyleOptionButton::DefaultButton) && (button->state & State_Enabled);
                isFlat = (button->features & QStyleOptionButton::Flat);
            }

            if (isFlat && !isDown) {
                if (isDefault) {
                    r = option->rect.adjusted(0, 1, 0, -1);
                    painter->setPen(QPen(Qt::black, 0));
                    const QLine lines[4] = {
                        QLine(QPoint(r.left() + 2, r.top()),
                              QPoint(r.right() - 2, r.top())),
                        QLine(QPoint(r.left(), r.top() + 2),
                              QPoint(r.left(), r.bottom() - 2)),
                        QLine(QPoint(r.right(), r.top() + 2),
                              QPoint(r.right(), r.bottom() - 2)),
                        QLine(QPoint(r.left() + 2, r.bottom()),
                              QPoint(r.right() - 2, r.bottom()))
                    };
                    painter->drawLines(lines, 4);
                    const QPoint points[4] = {
                        QPoint(r.right() - 1, r.bottom() - 1),
                        QPoint(r.right() - 1, r.top() + 1),
                        QPoint(r.left() + 1, r.bottom() - 1),
                        QPoint(r.left() + 1, r.top() + 1)
                    };
                    painter->drawPoints(points, 4);
                    painter->setPen(oldPen);
                }
                return;
            }

            BEGIN_STYLE_PIXMAPCACHE(QString::fromLatin1("pushbutton-%1").arg(isDefault))
            r = rect.adjusted(0, 1, 0, -1);

            bool isEnabled = (option->state & State_Enabled);

            QColor highlightedGradientStartColor = option->palette.button().color().lighter(107);
            QColor highlightedGradientMidColor = option->palette.button().color().lighter(105);
            QColor highlightedGradientStopColor = buttonShadow.lighter(107);
            QColor gradientStartColor = option->palette.button().color().lighter(108);

            QColor buttonColor = option->palette.button().color();
            QColor gradientMidColor = option->palette.button().color();
            QColor gradientStopColor;
            gradientStopColor.setHsv(buttonColor.hue(),
                                     qMin(255, (int)(buttonColor.saturation()*1.9)),
                                     qMin(255, (int)(buttonColor.value()*0.96)));

            QRect gradRect = rect.adjusted(1, 2, -1, -2);
            // gradient fill
            QRect innerBorder = r.adjusted(1, 1, -1, 0);

            if (isDown) {
                QBrush fillColor = gradientStopColor.darker(110);
                if (option->palette.button().gradient())
                    fillColor = option->palette.button();
                p->fillRect(gradRect, fillColor);
                p->setPen(gradientStopColor.darker(125));
                p->drawLine(innerBorder.topLeft(), innerBorder.topRight());
                p->drawLine(innerBorder.topLeft(), innerBorder.bottomLeft());
            } else {
                if (isEnabled && option->state & State_MouseOver ) {
                    qt_cleanlooks_draw_buttongradient(p, gradRect,
                                                highlightedGradientStartColor,
                                                highlightedGradientMidColor,
                                                highlightedGradientStopColor, TopDown, option->palette.button());
                } else {
                    qt_cleanlooks_draw_buttongradient(p, gradRect,
                                                gradientStartColor,
                                                gradientMidColor,
                                                gradientStopColor, TopDown, option->palette.button());
                }
            }

            bool hasFocus = option->state & State_HasFocus;

            if (!isEnabled)
                p->setPen(QPen(dark.lighter(115)));
            else if (isDefault)
                p->setPen(QPen(Qt::black, 1));
            else
                p->setPen(QPen(darkOutline, 1));

            p->drawLine(QPoint(r.left(), r.top() + 2),
                              QPoint(r.left(), r.bottom() - 2));
            p->drawLine(QPoint(r.right(), r.top() + 2),
                              QPoint(r.right(), r.bottom() - 2));
            p->drawLine(QPoint(r.left() + 2, r.bottom()),
                              QPoint(r.right() - 2, r.bottom()));
            const QPoint points[4] = {
                QPoint(r.right() - 1, r.bottom() - 1),
                QPoint(r.right() - 1, r.top() + 1),
                QPoint(r.left() + 1, r.bottom() - 1),
                QPoint(r.left() + 1, r.top() + 1)
            };
            p->drawPoints(points, 4);

            if (!isDefault && !hasFocus && isEnabled)
                p->setPen(QPen(darkOutline.darker(110), 0));

            p->drawLine(QPoint(r.left() + 2, r.top()),
                              QPoint(r.right() - 2, r.top()));

            QColor highlight = Qt::white;
            highlight.setAlpha(110);
            p->setPen(highlight);
            p->drawLine(QPoint(r.left() + 1, r.top() + 2),
                              QPoint(r.left() + 1, r.bottom() - 2));
            p->drawLine(QPoint(r.left() + 3, r.bottom() + 1),
                              QPoint(r.right() - 3, r.bottom() + 1));

            QColor topShadow = darkOutline;
            topShadow.setAlpha(60);

            p->setPen(topShadow);
            const QPoint points2[8] = {
                QPoint(r.right(), r.top() + 1),
                QPoint(r.right() - 1, r.top() ),
                QPoint(r.right(), r.bottom() - 1),
                QPoint(r.right() - 1, r.bottom() ),
                QPoint(r.left() + 1, r.bottom()),
                QPoint(r.left(), r.bottom() - 1),
                QPoint(r.left() + 1, r.top()),
                QPoint(r.left(), r.top() + 1)
            };
            p->drawPoints(points2, 8);

            topShadow.setAlpha(30);
            p->setPen(topShadow);

            p->drawLine(QPoint(r.right() - 1, r.top() + 2),
                              QPoint(r.right() - 1, r.bottom() - 2));
            p->drawLine(QPoint(r.left() + 2, r.top() - 1),
                              QPoint(r.right() - 2, r.top() - 1));

            if (isDefault) {
                r.adjust(-1, -1, 1, 1);
                p->setPen(buttonShadowAlpha.darker(120));
                const QLine lines[4] = {
                    QLine(r.topLeft() + QPoint(3, 0), r.topRight() - QPoint(3, 0)),
                    QLine(r.bottomLeft() + QPoint(3, 0), r.bottomRight() - QPoint(3, 0)),
                    QLine(r.topLeft() + QPoint(0, 3), r.bottomLeft() - QPoint(0, 3)),
                    QLine(r.topRight() + QPoint(0, 3), r.bottomRight() - QPoint(0, 3))
                };
                p->drawLines(lines, 4);
                const QPoint points3[8] = {
                    r.topRight() + QPoint(-2, 1),
                    r.topRight() + QPoint(-1, 2),
                    r.bottomRight() + QPoint(-1, -2),
                    r.bottomRight() + QPoint(-2, -1),
                    r.topLeft() + QPoint(1, 2),
                    r.topLeft() + QPoint(2, 1),
                    r.bottomLeft() + QPoint(1, -2),
                    r.bottomLeft() + QPoint(2, -1)
                };
                p->drawPoints(points3, 8);
            }
            painter->setPen(oldPen);
            painter->setBrush(oldBrush);
            END_STYLE_PIXMAPCACHE
        }
        break;
#ifndef QT_NO_TABBAR
        case PE_FrameTabWidget:
            painter->save();
        {
            painter->fillRect(option->rect, tabFrameColor);
        }
#ifndef QT_NO_TABWIDGET
        if (const QStyleOptionTabWidgetFrame *twf = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(option)) {
            QColor borderColor = darkOutline.lighter(110);
            QColor alphaCornerColor = mergedColors(borderColor, option->palette.background().color());

            int borderThickness = proxy()->pixelMetric(PM_TabBarBaseOverlap, twf, widget);
            bool reverse = (twf->direction == Qt::RightToLeft);
            QRect tabBarRect;

            switch (twf->shape) {
            case QTabBar::RoundedNorth:
                if (reverse) {
                    tabBarRect = QRect(twf->rect.right() - twf->leftCornerWidgetSize.width()
                                       - twf->tabBarSize.width() + 1,
                                       twf->rect.top(),
                                       twf->tabBarSize.width(), borderThickness);
                } else {
                    tabBarRect = QRect(twf->rect.left() + twf->leftCornerWidgetSize.width(),
                                       twf->rect.top(),
                                       twf->tabBarSize.width(), borderThickness);
                }
                break ;
            case QTabBar::RoundedWest:
                tabBarRect = QRect(twf->rect.left(),
                                   twf->rect.top() + twf->leftCornerWidgetSize.height(),
                                   borderThickness,
                                   twf->tabBarSize.height());
                tabBarRect = tabBarRect; //adjust
                break ;
            case QTabBar::RoundedEast:
                tabBarRect = QRect(twf->rect.right() - borderThickness + 1,
                                   twf->rect.top()  + twf->leftCornerWidgetSize.height(),
                                   0,
                                   twf->tabBarSize.height());
                break ;
            case QTabBar::RoundedSouth:
                if (reverse) {
                    tabBarRect = QRect(twf->rect.right() - twf->leftCornerWidgetSize.width() - twf->tabBarSize.width() + 1,
                                       twf->rect.bottom() + 1,
                                       twf->tabBarSize.width(),
                                       borderThickness);
                } else {
                    tabBarRect = QRect(twf->rect.left() + twf->leftCornerWidgetSize.width(),
                                       twf->rect.bottom() + 1,
                                       twf->tabBarSize.width(),
                                       borderThickness);
                }
                break;
            default:
                break;
            }

            QRegion region(twf->rect);
            region -= tabBarRect;
            painter->setClipRegion(region);

            // Outer border
            QLine leftLine = QLine(twf->rect.topLeft() + QPoint(0, 2), twf->rect.bottomLeft() - QPoint(0, 2));
            QLine rightLine = QLine(twf->rect.topRight(), twf->rect.bottomRight() - QPoint(0, 2));
            QLine bottomLine = QLine(twf->rect.bottomLeft() + QPoint(2, 0), twf->rect.bottomRight() - QPoint(2, 0));
            QLine topLine = QLine(twf->rect.topLeft(), twf->rect.topRight());

            painter->setPen(borderColor);
            painter->drawLine(topLine);

            // Inner border
            QLine innerLeftLine = QLine(leftLine.p1() + QPoint(1, 0), leftLine.p2() + QPoint(1, 0));
            QLine innerRightLine = QLine(rightLine.p1() - QPoint(1, -1), rightLine.p2() - QPoint(1, 0));
            QLine innerBottomLine = QLine(bottomLine.p1() - QPoint(0, 1), bottomLine.p2() - QPoint(0, 1));
            QLine innerTopLine = QLine(topLine.p1() + QPoint(0, 1), topLine.p2() + QPoint(-1, 1));

            // Rounded Corner
            QPoint leftBottomOuterCorner = QPoint(innerLeftLine.p2() + QPoint(0, 1));
            QPoint leftBottomInnerCorner1 = QPoint(leftLine.p2() + QPoint(0, 1));
            QPoint leftBottomInnerCorner2 = QPoint(bottomLine.p1() - QPoint(1, 0));
            QPoint rightBottomOuterCorner = QPoint(innerRightLine.p2() + QPoint(0, 1));
            QPoint rightBottomInnerCorner1 = QPoint(rightLine.p2() + QPoint(0, 1));
            QPoint rightBottomInnerCorner2 = QPoint(bottomLine.p2() + QPoint(1, 0));
            QPoint leftTopOuterCorner = QPoint(innerLeftLine.p1() - QPoint(0, 1));
            QPoint leftTopInnerCorner1 = QPoint(leftLine.p1() - QPoint(0, 1));
            QPoint leftTopInnerCorner2 = QPoint(topLine.p1() - QPoint(1, 0));

            painter->setPen(borderColor);
            painter->drawLine(leftLine);
            painter->drawLine(rightLine);
            painter->drawLine(bottomLine);
            painter->drawPoint(leftBottomOuterCorner);
            painter->drawPoint(rightBottomOuterCorner);
            painter->drawPoint(leftTopOuterCorner);

            painter->setPen(option->palette.light().color());
            painter->drawLine(innerLeftLine);
            painter->drawLine(innerTopLine);

            painter->setPen(buttonShadowAlpha);
            painter->drawLine(innerRightLine);
            painter->drawLine(innerBottomLine);

            painter->setPen(alphaCornerColor);
            const QPoint points[6] = {
                leftBottomInnerCorner1,
                leftBottomInnerCorner2,
                rightBottomInnerCorner1,
                rightBottomInnerCorner2,
                leftTopInnerCorner1,
                leftTopInnerCorner2
            };
            painter->drawPoints(points, 6);
        }
#endif // QT_NO_TABWIDGET
    painter->restore();
    break ;

    case PE_FrameStatusBarItem:
        break;
    case PE_IndicatorTabClose:
        {
            Q_D(const QCleanlooksStyle);
            if (d->tabBarcloseButtonIcon.isNull())
                d->tabBarcloseButtonIcon = standardIcon(SP_DialogCloseButton, option, widget);
            if ((option->state & State_Enabled) && (option->state & State_MouseOver))
                proxy()->drawPrimitive(PE_PanelButtonCommand, option, painter, widget);
            QPixmap pixmap = d->tabBarcloseButtonIcon.pixmap(QSize(16, 16), QIcon::Normal, QIcon::On);
            proxy()->drawItemPixmap(painter, option->rect, Qt::AlignCenter, pixmap);
        }
        break;

#endif // QT_NO_TABBAR
    default:
        QWindowsStyle::drawPrimitive(elem, option, painter, widget);
        break;
    }
}

/*!
  \reimp
*/
void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter,
                                   const QWidget *widget) const
{
    QColor button = option->palette.button().color();
    QColor dark;
    dark.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*1.9)),
                qMin(255, (int)(button.value()*0.7)));
    QColor darkOutline;
    darkOutline.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*2.0)),
                qMin(255, (int)(button.value()*0.6)));
    QRect rect = option->rect;
    QColor shadow = mergedColors(option->palette.background().color().darker(120),
                                 dark.lighter(130), 60);
    QColor tabFrameColor = mergedColors(option->palette.background().color(),
                                                dark.lighter(135), 60);

    QColor highlight = option->palette.highlight().color();

    switch(element) {
     case CE_RadioButton: //fall through
     case CE_CheckBox:
        if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
            bool hover = (btn->state & State_MouseOver && btn->state & State_Enabled);
            if (hover)
                painter->fillRect(rect, btn->palette.background().color().lighter(104));
            QStyleOptionButton copy = *btn;
            copy.rect.adjust(2, 0, -2, 0);
            QWindowsStyle::drawControl(element, &copy, painter, widget);
        }
        break;
    case CE_Splitter:
        painter->save();
        {
            // hover appearance
            QBrush fillColor = option->palette.background().color();
            if (option->state & State_MouseOver && option->state & State_Enabled)
                fillColor = fillColor.color().lighter(106);

            painter->fillRect(option->rect, fillColor);

            QColor grooveColor = mergedColors(dark.lighter(110), option->palette.button().color(),40);
            QColor gripShadow = grooveColor.darker(110);
            QPalette palette = option->palette;
            bool vertical = !(option->state & State_Horizontal);
            QRect scrollBarSlider = option->rect;
            int gripMargin = 4;
            //draw grips
            if (vertical) {
                for( int i = -20; i< 20 ; i += 2) {
                    painter->setPen(QPen(gripShadow, 1));
                    painter->drawLine(
                        QPoint(scrollBarSlider.center().x() + i ,
                               scrollBarSlider.top() + gripMargin),
                        QPoint(scrollBarSlider.center().x() + i,
                               scrollBarSlider.bottom() - gripMargin));
                    painter->setPen(QPen(palette.light(), 1));
                    painter->drawLine(
                        QPoint(scrollBarSlider.center().x() + i + 1,
                               scrollBarSlider.top() + gripMargin  ),
                        QPoint(scrollBarSlider.center().x() + i + 1,
                               scrollBarSlider.bottom() - gripMargin));
                }
            } else {
                for (int i = -20; i < 20 ; i += 2) {
                    painter->setPen(QPen(gripShadow, 1));
                    painter->drawLine(
                        QPoint(scrollBarSlider.left() + gripMargin ,
                               scrollBarSlider.center().y()+ i),
                        QPoint(scrollBarSlider.right() - gripMargin,
                               scrollBarSlider.center().y()+ i));
                    painter->setPen(QPen(palette.light(), 1));
                    painter->drawLine(
                        QPoint(scrollBarSlider.left() + gripMargin,
                               scrollBarSlider.center().y() + 1 + i),
                        QPoint(scrollBarSlider.right() - gripMargin,
                               scrollBarSlider.center().y() + 1 + i));

                }
            }
        }
        painter->restore();
        break;
#ifndef QT_NO_SIZEGRIP
    case CE_SizeGrip:
        painter->save();
        {
            int x, y, w, h;
            option->rect.getRect(&x, &y, &w, &h);
            int sw = qMin(h, w);
            if (h > w)
                painter->translate(0, h - w);
            else
                painter->translate(w - h, 0);

            int sx = x;
            int sy = y;
            int s = 4;
            if (option->direction == Qt::RightToLeft) {
                sx = x + sw;
                for (int i = 0; i < 4; ++i) {
                    painter->setPen(QPen(option->palette.light().color(), 1));
                    painter->drawLine(x, sy - 1 , sx + 1, sw);
                    painter->setPen(QPen(dark.lighter(120), 1));
                    painter->drawLine(x, sy, sx, sw);
                    sx -= s;
                    sy += s;
                }
            } else {
                for (int i = 0; i < 4; ++i) {
                    painter->setPen(QPen(option->palette.light().color(), 1));
                    painter->drawLine(sx - 1, sw, sw, sy - 1);
                    painter->setPen(QPen(dark.lighter(120), 1));
                    painter->drawLine(sx, sw, sw, sy);
                    sx += s;
                    sy += s;
                }
            }
        }
        painter->restore();
        break;
#endif // QT_NO_SIZEGRIP
#ifndef QT_NO_TOOLBAR
    case CE_ToolBar:
        painter->save();
        if (const QStyleOptionToolBar *toolbar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
            QRect rect = option->rect;

            bool paintLeftBorder = true;
            bool paintRightBorder = true;
            bool paintBottomBorder = true;

            switch (toolbar->toolBarArea) {
            case Qt::BottomToolBarArea:
                switch(toolbar->positionOfLine) {
                case QStyleOptionToolBar::Beginning:
                case QStyleOptionToolBar::OnlyOne:
                    paintBottomBorder = false;
                default:
                    break;
                }
            case Qt::TopToolBarArea:
                switch (toolbar->positionWithinLine) {
                case QStyleOptionToolBar::Beginning:
                    paintLeftBorder = false;
                    break;
                case QStyleOptionToolBar::End:
                    paintRightBorder = false;
                    break;
                case QStyleOptionToolBar::OnlyOne:
                    paintRightBorder = false;
                    paintLeftBorder = false;
                default:
                    break;
                }
                if (toolbar->direction == Qt::RightToLeft) { //reverse layout changes the order of Beginning/end
                    bool tmp = paintLeftBorder;
                    paintRightBorder=paintLeftBorder;
                    paintLeftBorder=tmp;
                }
                break;
            case Qt::RightToolBarArea:
                switch (toolbar->positionOfLine) {
                case QStyleOptionToolBar::Beginning:
                case QStyleOptionToolBar::OnlyOne:
                    paintRightBorder = false;
                    break;
                default:
                    break;
                }
                break;
            case Qt::LeftToolBarArea:
                switch (toolbar->positionOfLine) {
                case QStyleOptionToolBar::Beginning:
                case QStyleOptionToolBar::OnlyOne:
                    paintLeftBorder = false;
                    break;
                default:
                    break;
                }
                break;
            default:
                break;
            }

            QColor light = option->palette.background().color().lighter(110);

            //draw top border
            painter->setPen(QPen(light));
            painter->drawLine(rect.topLeft().x(),
                        rect.topLeft().y(),
                        rect.topRight().x(),
                        rect.topRight().y());

            if (paintLeftBorder) {
                painter->setPen(QPen(light));
                painter->drawLine(rect.topLeft().x(),
                            rect.topLeft().y(),
                            rect.bottomLeft().x(),
                            rect.bottomLeft().y());
            }

            if (paintRightBorder) {
                painter->setPen(QPen(shadow));
                painter->drawLine(rect.topRight().x(),
                            rect.topRight().y(),
                            rect.bottomRight().x(),
                            rect.bottomRight().y());
            }

            if (paintBottomBorder) {
                painter->setPen(QPen(shadow));
                painter->drawLine(rect.bottomLeft().x(),
                            rect.bottomLeft().y(),
                            rect.bottomRight().x(),
                            rect.bottomRight().y());
            }
        }
        painter->restore();
        break;
#endif // QT_NO_TOOLBAR
#ifndef QT_NO_DOCKWIDGET
    case CE_DockWidgetTitle:
        painter->save();
        if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(option)) {
            const QStyleOptionDockWidgetV2 *v2
                = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
            bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;

            QRect rect = dwOpt->rect;
            QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, option, widget);
            QRect r = rect.adjusted(0, 0, -1, 0);
            if (verticalTitleBar)
                r.adjust(0, 0, 0, -1);
            painter->setPen(option->palette.light().color());
            painter->drawRect(r.adjusted(1, 1, 1, 1));
            painter->setPen(shadow);
            painter->drawRect(r);

            if (verticalTitleBar) {
                QRect r = rect;
                QSize s = r.size();
                s.transpose();
                r.setSize(s);

                titleRect = QRect(r.left() + rect.bottom()
                                    - titleRect.bottom(),
                                r.top() + titleRect.left() - rect.left(),
                                titleRect.height(), titleRect.width());

                painter->translate(r.left(), r.top() + r.width());
                painter->rotate(-90);
                painter->translate(-r.left(), -r.top());

                rect = r;
            }

            if (!dwOpt->title.isEmpty()) {
                QString titleText
                    = painter->fontMetrics().elidedText(dwOpt->title,
                                            Qt::ElideRight, titleRect.width());
                proxy()->drawItemText(painter,
                             titleRect,
                             Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, dwOpt->palette,
                             dwOpt->state & State_Enabled, titleText,
                             QPalette::WindowText);
                }
        }
        painter->restore();
        break;
#endif // QT_NO_DOCKWIDGET
    case CE_HeaderSection:
        painter->save();
        // Draws the header in tables.
        if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option)) {
            QPixmap cache;
            QString pixmapName = QStyleHelper::uniqueName(QLatin1String("headersection"), option, option->rect.size());
            pixmapName += QString::number(- int(header->position));
            pixmapName += QString::number(- int(header->orientation));
            QRect r = option->rect;
            QColor gradientStopColor;
            QColor gradientStartColor = option->palette.button().color();
            gradientStopColor.setHsv(gradientStartColor.hue(),
                                     qMin(255, (int)(gradientStartColor.saturation()*2)),
                                     qMin(255, (int)(gradientStartColor.value()*0.96)));
            QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
            if (option->palette.background().gradient()) {
                gradient.setStops(option->palette.background().gradient()->stops());
            } else {
                gradient.setColorAt(0, gradientStartColor);
                gradient.setColorAt(0.8, gradientStartColor);
                gradient.setColorAt(1, gradientStopColor);
            }
            painter->fillRect(r, gradient);

            if (!QPixmapCache::find(pixmapName, cache)) {
                cache = QPixmap(r.size());
                cache.fill(Qt::transparent);
                QRect pixmapRect(0, 0, r.width(), r.height());
                QPainter cachePainter(&cache);
                if (header->orientation == Qt::Vertical) {
                    cachePainter.setPen(QPen(dark));
                    cachePainter.drawLine(pixmapRect.topRight(), pixmapRect.bottomRight());
                    if (header->position != QStyleOptionHeader::End) {
                        cachePainter.setPen(QPen(shadow));
                        cachePainter.drawLine(pixmapRect.bottomLeft() + QPoint(3, -1), pixmapRect.bottomRight() + QPoint(-3, -1));                                cachePainter.setPen(QPen(option->palette.light().color()));
                        cachePainter.drawLine(pixmapRect.bottomLeft() + QPoint(3, 0), pixmapRect.bottomRight() + QPoint(-3, 0));                              }
                } else {
                    cachePainter.setPen(QPen(dark));
                    cachePainter.drawLine(pixmapRect.bottomLeft(), pixmapRect.bottomRight());
                    cachePainter.setPen(QPen(shadow));
                    cachePainter.drawLine(pixmapRect.topRight() + QPoint(-1, 3), pixmapRect.bottomRight() + QPoint(-1, -3));                                  cachePainter.setPen(QPen(option->palette.light().color()));
                    cachePainter.drawLine(pixmapRect.topRight() + QPoint(0, 3), pixmapRect.bottomRight() + QPoint(0, -3));                                }
                cachePainter.end();
                QPixmapCache::insert(pixmapName, cache);
            }
            painter->drawPixmap(r.topLeft(), cache);
        }
        painter->restore();
        break;
    case CE_ProgressBarGroove:
        painter->save();
        {
            painter->fillRect(rect, option->palette.base());
            QColor borderColor = dark.lighter(110);
            painter->setPen(QPen(borderColor, 0));
            const QLine lines[4] = {
                QLine(QPoint(rect.left() + 1, rect.top()), QPoint(rect.right() - 1, rect.top())),
                QLine(QPoint(rect.left() + 1, rect.bottom()), QPoint(rect.right() - 1, rect.bottom())),
                QLine(QPoint(rect.left(), rect.top() + 1), QPoint(rect.left(), rect.bottom() - 1)),
                QLine(QPoint(rect.right(), rect.top() + 1), QPoint(rect.right(), rect.bottom() - 1))
            };
            painter->drawLines(lines, 4);
            QColor alphaCorner = mergedColors(borderColor, option->palette.background().color());
            QColor innerShadow = mergedColors(borderColor, option->palette.base().color());

            //corner smoothing
            painter->setPen(alphaCorner);
            const QPoint points[4] = {
                rect.topRight(),
                rect.topLeft(),
                rect.bottomRight(),
                rect.bottomLeft()
            };
            painter->drawPoints(points, 4);

            //inner shadow
            painter->setPen(innerShadow);
            painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1),
                              QPoint(rect.right() - 1, rect.top() + 1));
            painter->drawLine(QPoint(rect.left() + 1, rect.top() + 1),
                              QPoint(rect.left() + 1, rect.bottom() + 1));

        }
        painter->restore();
        break;
    case CE_ProgressBarContents:
        painter->save();
        if (const QStyleOptionProgressBar *bar = qstyleoption_cast<const QStyleOptionProgressBar *>(option)) {
            QRect rect = bar->rect;
            bool vertical = false;
            bool inverted = false;
            bool indeterminate = (bar->minimum == 0 && bar->maximum == 0);

            // Get extra style options if version 2
            if (const QStyleOptionProgressBarV2 *bar2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(option)) {
                vertical = (bar2->orientation == Qt::Vertical);
                inverted = bar2->invertedAppearance;
            }

            // If the orientation is vertical, we use a transform to rotate
            // the progress bar 90 degrees clockwise.  This way we can use the
            // same rendering code for both orientations.
            if (vertical) {
                rect = QRect(rect.left(), rect.top(), rect.height(), rect.width()); // flip width and height
                QTransform m = QTransform::fromTranslate(rect.height()-1, -1.0);
                m.rotate(90.0);
                painter->setTransform(m, true);
            }

            int maxWidth = rect.width() - 4;
            int minWidth = 4;
            qreal progress = qMax(bar->progress, bar->minimum); // workaround for bug in QProgressBar
            int progressBarWidth = (progress - bar->minimum) * qreal(maxWidth) / qMax(qreal(1.0), qreal(bar->maximum) - bar->minimum);
            int width = indeterminate ? maxWidth : qMax(minWidth, progressBarWidth);

            bool reverse = (!vertical && (bar->direction == Qt::RightToLeft)) || vertical;
            if (inverted)
                reverse = !reverse;

            QRect progressBar;
            if (!indeterminate) {
                if (!reverse) {
                    progressBar.setRect(rect.left() + 1, rect.top() + 1, width + 1, rect.height() - 3);
                } else {
                    progressBar.setRect(rect.right() - 1 - width, rect.top() + 1, width + 1, rect.height() - 3);
                }
            } else {
                Q_D(const QCleanlooksStyle);
                int slideWidth = ((rect.width() - 4) * 2) / 3;
                int step = ((d->animateStep * slideWidth) / d->animationFps) % slideWidth;
                if ((((d->animateStep * slideWidth) / d->animationFps) % (2 * slideWidth)) >= slideWidth)
                    step = slideWidth - step;
                progressBar.setRect(rect.left() + 1 + step, rect.top() + 1,
                                    slideWidth / 2, rect.height() - 3);
            }
            QColor highlight = option->palette.color(QPalette::Normal, QPalette::Highlight);
            painter->setPen(QPen(highlight.darker(140), 0));

            QColor highlightedGradientStartColor = highlight.lighter(100);
            QColor highlightedGradientStopColor  = highlight.lighter(130);

            QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(),
                                                            rect.bottomLeft().y()*2));

            gradient.setColorAt(0, highlightedGradientStartColor);
            gradient.setColorAt(1, highlightedGradientStopColor);

            painter->setBrush(gradient);
            painter->drawRect(progressBar);

            painter->setPen(QPen(highlight.lighter(120), 0));
            painter->drawLine(QPoint(progressBar.left() + 1, progressBar.top() + 1),
                              QPoint(progressBar.right(), progressBar.top() + 1));
            painter->drawLine(QPoint(progressBar.left() + 1, progressBar.top() + 1),
                              QPoint(progressBar.left() + 1, progressBar.bottom() - 1));

            painter->setPen(QPen(highlightedGradientStartColor, 7.0));//QPen(option->palette.highlight(), 3));

            painter->save();
            painter->setClipRect(progressBar.adjusted(2, 2, -1, -1));
            for (int x = progressBar.left() - 32; x < rect.right() ; x+=18) {
                painter->drawLine(x, progressBar.bottom() + 1, x + 23, progressBar.top() - 2);
            }
            painter->restore();

        }
        painter->restore();
        break;
    case CE_MenuBarItem:
        painter->save();
        if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option))
        {
            QStyleOptionMenuItem item = *mbi;
            item.rect = mbi->rect.adjusted(0, 3, 0, -1);
            QColor highlightOutline = highlight.darker(125);
            QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(), rect.bottomLeft().y()*2));

            if (option->palette.button().gradient()) {
                gradient.setStops(option->palette.button().gradient()->stops());
            } else {
                gradient.setColorAt(0, option->palette.button().color());
                gradient.setColorAt(1, option->palette.button().color().darker(110));
            }
            painter->fillRect(rect, gradient);

            QCommonStyle::drawControl(element, &item, painter, widget);

            bool act = mbi->state & State_Selected && mbi->state & State_Sunken;
            bool dis = !(mbi->state & State_Enabled);

            QRect r = option->rect;
            if (act) {
                qt_cleanlooks_draw_gradient(painter, r.adjusted(1, 1, -1, -1),
                                            highlight,
                                            highlightOutline, TopDown,
                                            option->palette.highlight());

                painter->setPen(QPen(highlightOutline, 0));
                const QLine lines[4] = {
                    QLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom())),
                    QLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom())),
                    QLine(QPoint(r.left() + 1, r.bottom()), QPoint(r.right() - 1, r.bottom())),
                    QLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top()))
                };
                painter->drawLines(lines, 4);

                //draw text
                QPalette::ColorRole textRole = dis ? QPalette::Text : QPalette::HighlightedText;
                uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
                if (!styleHint(SH_UnderlineShortcut, mbi, widget))
                    alignment |= Qt::TextHideMnemonic;
                proxy()->drawItemText(painter, item.rect, alignment, mbi->palette, mbi->state & State_Enabled, mbi->text, textRole);
            }

        }
        painter->restore();
        break;
    case CE_MenuItem:
        painter->save();
        // Draws one item in a popup menu.
        if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
            QColor highlightOutline = highlight.darker(125);
            QColor menuBackground = option->palette.background().color().lighter(104);
            QColor borderColor = option->palette.background().color().darker(160);
            QColor alphaCornerColor;

            if (widget) {
                // ### backgroundrole/foregroundrole should be part of the style option
                alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), borderColor);
            } else {
                alphaCornerColor = mergedColors(option->palette.background().color(), borderColor);
            }
            if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
                painter->fillRect(menuItem->rect, menuBackground);
                int w = 0;
                if (!menuItem->text.isEmpty()) {
                    painter->setFont(menuItem->font);
                    proxy()->drawItemText(painter, menuItem->rect.adjusted(5, 0, -5, 0), Qt::AlignLeft | Qt::AlignVCenter,
                                 menuItem->palette, menuItem->state & State_Enabled, menuItem->text,
                                 QPalette::Text);
                    w = menuItem->fontMetrics.width(menuItem->text) + 5;
                }
                painter->setPen(shadow.lighter(106));
                bool reverse = menuItem->direction == Qt::RightToLeft;
                painter->drawLine(menuItem->rect.left() + 5 + (reverse ? 0 : w), menuItem->rect.center().y(),
                                  menuItem->rect.right() - 5 - (reverse ? w : 0), menuItem->rect.center().y());
                painter->restore();
                break;
            }
            bool selected = menuItem->state & State_Selected && menuItem->state & State_Enabled;
            if (selected) {
                QRect r = option->rect.adjusted(1, 0, -2, -1);
                qt_cleanlooks_draw_gradient(painter, r, highlight,
                                            highlightOutline, TopDown,
                                            highlight);
                r = r.adjusted(-1, 0, 1, 0);
                painter->setPen(QPen(highlightOutline, 0));
                const QLine lines[4] = {
                    QLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom() - 1)),
                    QLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom() - 1)),
                    QLine(QPoint(r.left() + 1, r.bottom()), QPoint(r.right() - 1, r.bottom())),
                    QLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top()))
                };
                painter->drawLines(lines, 4);
            } else {
                painter->fillRect(option->rect, menuBackground);
            }

            bool checkable = menuItem->checkType != QStyleOptionMenuItem::NotCheckable;
            bool checked = menuItem->checked;
            bool sunken = menuItem->state & State_Sunken;
            bool enabled = menuItem->state & State_Enabled;

            bool ignoreCheckMark = false;
            int checkcol = qMax(menuItem->maxIconWidth, 20);

#ifndef QT_NO_COMBOBOX
            if (qobject_cast<const QComboBox*>(widget))
                ignoreCheckMark = true; //ignore the checkmarks provided by the QComboMenuDelegate
#endif

            if (!ignoreCheckMark) {
                // Check
                QRect checkRect(option->rect.left() + 7, option->rect.center().y() - 6, 13, 13);
                checkRect = visualRect(menuItem->direction, menuItem->rect, checkRect);
                if (checkable) {
                    if (menuItem->checkType & QStyleOptionMenuItem::Exclusive) {
                        // Radio button
                        if (checked || sunken) {
                            painter->setRenderHint(QPainter::Antialiasing);
                            painter->setPen(Qt::NoPen);

                            QPalette::ColorRole textRole = !enabled ? QPalette::Text:
                                                        selected ? QPalette::HighlightedText : QPalette::ButtonText;
                            painter->setBrush(option->palette.brush( option->palette.currentColorGroup(), textRole));
                            painter->drawEllipse(checkRect.adjusted(4, 4, -4, -4));
                        }
                    } else {
                        // Check box
                        if (menuItem->icon.isNull()) {
                            if (checked || sunken) {
                                QImage image(qt_cleanlooks_menuitem_checkbox_checked);
                                if (enabled && (menuItem->state & State_Selected)) {
                                    image.setColor(1, 0x55ffffff);
                                    image.setColor(2, 0xAAffffff);
                                    image.setColor(3, 0xBBffffff);
                                    image.setColor(4, 0xFFffffff);
                                    image.setColor(5, 0x33ffffff);
                                } else {
                                    image.setColor(1, 0x55000000);
                                    image.setColor(2, 0xAA000000);
                                    image.setColor(3, 0xBB000000);
                                    image.setColor(4, 0xFF000000);
                                    image.setColor(5, 0x33000000);
                                }
                                painter->drawImage(QPoint(checkRect.center().x() - image.width() / 2,
                                                        checkRect.center().y() - image.height() / 2), image);
                            }
                        }
                    }
                }
            } else { //ignore checkmark
                if (menuItem->icon.isNull())
                    checkcol = 0;
                else
                    checkcol = menuItem->maxIconWidth;
            }

            // Text and icon, ripped from windows style
            bool dis = !(menuItem->state & State_Enabled);
            bool act = menuItem->state & State_Selected;
            const QStyleOption *opt = option;
            const QStyleOptionMenuItem *menuitem = menuItem;

            QPainter *p = painter;
            QRect vCheckRect = visualRect(opt->direction, menuitem->rect,
                                          QRect(menuitem->rect.x(), menuitem->rect.y(),
                                                checkcol, menuitem->rect.height()));
            if (!menuItem->icon.isNull()) {
                QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
                if (act && !dis)
                    mode = QIcon::Active;
                QPixmap pixmap;

                int smallIconSize = proxy()->pixelMetric(PM_SmallIconSize, option, widget);
                QSize iconSize(smallIconSize, smallIconSize);
#ifndef QT_NO_COMBOBOX
                if (const QComboBox *combo = qobject_cast<const QComboBox*>(widget))
                    iconSize = combo->iconSize();
#endif // QT_NO_COMBOBOX
                if (checked)
                    pixmap = menuItem->icon.pixmap(iconSize, mode, QIcon::On);
                else
                    pixmap = menuItem->icon.pixmap(iconSize, mode);

                int pixw = pixmap.width();
                int pixh = pixmap.height();

                QRect pmr(0, 0, pixw, pixh);
                pmr.moveCenter(vCheckRect.center());
                painter->setPen(menuItem->palette.text().color());
                if (checkable && checked) {
                    QStyleOption opt = *option;
                    if (act) {
                        QColor activeColor = mergedColors(option->palette.background().color(),
                                                        option->palette.highlight().color());
                        opt.palette.setBrush(QPalette::Button, activeColor);
                    }
                    opt.state |= State_Sunken;
                    opt.rect = vCheckRect;
                    proxy()->drawPrimitive(PE_PanelButtonCommand, &opt, painter, widget);
                }
                painter->drawPixmap(pmr.topLeft(), pixmap);
            }
            if (selected) {
                painter->setPen(menuItem->palette.highlightedText().color());
            } else {
                painter->setPen(menuItem->palette.text().color());
            }
            int x, y, w, h;
            menuitem->rect.getRect(&x, &y, &w, &h);
            int tab = menuitem->tabWidth;
            QColor discol;
            if (dis) {
                discol = menuitem->palette.text().color();
                p->setPen(discol);
            }
            int xm = windowsItemFrame + checkcol + windowsItemHMargin;
            int xpos = menuitem->rect.x() + xm;

            QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
            QRect vTextRect = visualRect(opt->direction, menuitem->rect, textRect);
            QString s = menuitem->text;
            if (!s.isEmpty()) {                     // draw text
                p->save();
                int t = s.indexOf(QLatin1Char('\t'));
                int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
                if (!styleHint(SH_UnderlineShortcut, menuitem, widget))
                    text_flags |= Qt::TextHideMnemonic;
                text_flags |= Qt::AlignLeft;
                if (t >= 0) {
                    QRect vShortcutRect = visualRect(opt->direction, menuitem->rect,
                                                     QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
                    if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
                        p->setPen(menuitem->palette.light().color());
                        p->drawText(vShortcutRect.adjusted(1, 1, 1, 1), text_flags, s.mid(t + 1));
                        p->setPen(discol);
                    }
                    p->drawText(vShortcutRect, text_flags, s.mid(t + 1));
                    s = s.left(t);
                }
                QFont font = menuitem->font;
                // font may not have any "hard" flags set. We override
                // the point size so that when it is resolved against the device, this font will win.
                // This is mainly to handle cases where someone sets the font on the window
                // and then the combo inherits it and passes it onward. At that point the resolve mask
                // is very, very weak. This makes it stonger.
                font.setPointSizeF(QFontInfo(menuItem->font).pointSizeF());

                if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem)
                    font.setBold(true);

                p->setFont(font);
                if (dis && !act && proxy()->styleHint(SH_EtchDisabledText, option, widget)) {
                    p->setPen(menuitem->palette.light().color());
                    p->drawText(vTextRect.adjusted(1, 1, 1, 1), text_flags, s.left(t));
                    p->setPen(discol);
                }
                p->drawText(vTextRect, text_flags, s.left(t));
                p->restore();
            }

            // Arrow
            if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
                int dim = (menuItem->rect.height() - 4) / 2;
                PrimitiveElement arrow;
                arrow = QApplication::isRightToLeft() ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
                int xpos = menuItem->rect.left() + menuItem->rect.width() - 3 - dim;
                QRect  vSubMenuRect = visualRect(option->direction, menuItem->rect,
                                                 QRect(xpos, menuItem->rect.top() + menuItem->rect.height() / 2 - dim / 2, dim, dim));
                QStyleOptionMenuItem newMI = *menuItem;
                newMI.rect = vSubMenuRect;
                newMI.state = !enabled ? State_None : State_Enabled;
                if (selected)
                    newMI.palette.setColor(QPalette::ButtonText,
                                           newMI.palette.highlightedText().color());
                proxy()->drawPrimitive(arrow, &newMI, painter, widget);
            }
        }
        painter->restore();
        break;
    case CE_MenuHMargin:
    case CE_MenuVMargin:
        break;
    case CE_MenuEmptyArea:
        break;
    case CE_PushButtonLabel:
        if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option)) {
            QRect ir = button->rect;
            uint tf = Qt::AlignVCenter;
            if (styleHint(SH_UnderlineShortcut, button, widget))
                tf |= Qt::TextShowMnemonic;
            else
               tf |= Qt::TextHideMnemonic;

            if (!button->icon.isNull()) {
                //Center both icon and text
                QPoint point;

                QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal
                                                              : QIcon::Disabled;
                if (mode == QIcon::Normal && button->state & State_HasFocus)
                    mode = QIcon::Active;
                QIcon::State state = QIcon::Off;
                if (button->state & State_On)
                    state = QIcon::On;

                QPixmap pixmap = button->icon.pixmap(button->iconSize, mode, state);
                int w = pixmap.width();
                int h = pixmap.height();

                if (!button->text.isEmpty())
                    w += button->fontMetrics.boundingRect(option->rect, tf, button->text).width() + 2;

                point = QPoint(ir.x() + ir.width() / 2 - w / 2,
                               ir.y() + ir.height() / 2 - h / 2);

                if (button->direction == Qt::RightToLeft)
                    point.rx() += pixmap.width();

                painter->drawPixmap(visualPos(button->direction, button->rect, point), pixmap);

                if (button->direction == Qt::RightToLeft)
                    ir.translate(-point.x() - 2, 0);
                else
                    ir.translate(point.x() + pixmap.width(), 0);

                // left-align text if there is
                if (!button->text.isEmpty())
                    tf |= Qt::AlignLeft;

            } else {
                tf |= Qt::AlignHCenter;
            }

            if (button->features & QStyleOptionButton::HasMenu)
                ir = ir.adjusted(0, 0, -proxy()->pixelMetric(PM_MenuButtonIndicator, button, widget), 0);
            proxy()->drawItemText(painter, ir, tf, button->palette, (button->state & State_Enabled),
                         button->text, QPalette::ButtonText);
        }
        break;
    case CE_MenuBarEmptyArea:
        painter->save();
        {
            QColor shadow = mergedColors(option->palette.background().color().darker(120),
                                 dark.lighter(140), 60);

            QLinearGradient gradient(rect.topLeft(), QPoint(rect.bottomLeft().x(), rect.bottomLeft().y()*2));
            gradient.setColorAt(0, option->palette.button().color());
            gradient.setColorAt(1, option->palette.button().color().darker(110));
            painter->fillRect(rect, gradient);

#ifndef QT_NO_MAINWINDOW
            if (widget && qobject_cast<const QMainWindow *>(widget->parentWidget())) {
                QPen oldPen = painter->pen();
                painter->setPen(QPen(shadow));
                painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
            }
#endif // QT_NO_MAINWINDOW
        }
        painter->restore();
        break;
#ifndef QT_NO_TABBAR
	case CE_TabBarTabShape:
        painter->save();
        if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(option)) {

            bool rtlHorTabs = (tab->direction == Qt::RightToLeft
                               && (tab->shape == QTabBar::RoundedNorth
                                   || tab->shape == QTabBar::RoundedSouth));
            bool selected = tab->state & State_Selected;
            bool lastTab = ((!rtlHorTabs && tab->position == QStyleOptionTab::End)
                            || (rtlHorTabs
                                && tab->position == QStyleOptionTab::Beginning));
            bool onlyTab = tab->position == QStyleOptionTab::OnlyOneTab;
            bool leftCornerWidget = (tab->cornerWidgets & QStyleOptionTab::LeftCornerWidget);

            bool atBeginning = ((tab->position == (tab->direction == Qt::LeftToRight ?
                                QStyleOptionTab::Beginning : QStyleOptionTab::End)) || onlyTab);

            bool onlyOne = tab->position == QStyleOptionTab::OnlyOneTab;
            bool previousSelected =
                ((!rtlHorTabs
                  && tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
                 || (rtlHorTabs
                     && tab->selectedPosition == QStyleOptionTab::NextIsSelected));
            bool nextSelected =
                ((!rtlHorTabs
                  && tab->selectedPosition == QStyleOptionTab::NextIsSelected)
                 || (rtlHorTabs
                     && tab->selectedPosition
                     == QStyleOptionTab::PreviousIsSelected));
            int tabBarAlignment = proxy()->styleHint(SH_TabBar_Alignment, tab, widget);
            bool leftAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignLeft)
                               || (rtlHorTabs
                                   && tabBarAlignment == Qt::AlignRight);

            bool rightAligned = (!rtlHorTabs && tabBarAlignment == Qt::AlignRight)
                                || (rtlHorTabs
                                    && tabBarAlignment == Qt::AlignLeft);

            QColor light = tab->palette.light().color();

            QColor background = tab->palette.background().color();
            int borderThinkness = proxy()->pixelMetric(PM_TabBarBaseOverlap, tab, widget);
            if (selected)
                borderThinkness /= 2;
            QRect r2(option->rect);
            int x1 = r2.left();
            int x2 = r2.right();
            int y1 = r2.top();
            int y2 = r2.bottom();

            QTransform rotMatrix;
            bool flip = false;
            painter->setPen(shadow);
            QColor activeHighlight = option->palette.color(QPalette::Normal, QPalette::Highlight);
            switch (tab->shape) {
            case QTabBar::RoundedNorth:
                break;
            case QTabBar::RoundedSouth:
                rotMatrix.rotate(180);
                rotMatrix.translate(0, -rect.height() + 1);
                rotMatrix.scale(-1, 1);
                painter->setTransform(rotMatrix, true);
                break;
            case QTabBar::RoundedWest:
                rotMatrix.rotate(180 + 90);
                rotMatrix.scale(-1, 1);
                flip = true;
                painter->setTransform(rotMatrix, true);
                break;
            case QTabBar::RoundedEast:
                rotMatrix.rotate(90);
                rotMatrix.translate(0, - rect.width() + 1);
                flip = true;
                painter->setTransform(rotMatrix, true);
                break;
            default:
                painter->restore();
                QWindowsStyle::drawControl(element, tab, painter, widget);
                return;
            }

            if (flip) {
                QRect tmp = rect;
                rect = QRect(tmp.y(), tmp.x(), tmp.height(), tmp.width());
                int temp = x1;
                x1 = y1;
                y1 = temp;
                temp = x2;
                x2 = y2;
                y2 = temp;
            }

            QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
            if (option->palette.button().gradient()) {
                if (selected)
                    gradient.setStops(option->palette.background().gradient()->stops());
                else
                    gradient.setStops(option->palette.background().gradient()->stops());
            }
            else if (selected) {
                gradient.setColorAt(0, option->palette.background().color().lighter(104));
                gradient.setColorAt(1, tabFrameColor);
                painter->fillRect(rect.adjusted(0, 2, 0, -1), gradient);
            } else {
                y1 += 2;
                gradient.setColorAt(0, option->palette.background().color());
                gradient.setColorAt(1, dark.lighter(120));
                painter->fillRect(rect.adjusted(0, 2, 0, -2), gradient);
            }

            // Delete border
            if (selected) {
                painter->setPen(QPen(activeHighlight, 0));
                painter->drawLine(x1 + 1, y1 + 1, x2 - 1, y1 + 1);
                painter->drawLine(x1 , y1 + 2, x2 , y1 + 2);
            } else {
                painter->setPen(dark);
                painter->drawLine(x1, y2 - 1, x2 + 2, y2 - 1 );
                if (tab->shape == QTabBar::RoundedNorth || tab->shape == QTabBar::RoundedWest) {
                    painter->setPen(light);
                    painter->drawLine(x1, y2 , x2, y2 );
                }
            }
            // Left
            if (atBeginning || selected ) {
                painter->setPen(light);
                painter->drawLine(x1 + 1, y1 + 2 + 1, x1 + 1, y2 - ((onlyOne || atBeginning) && selected && leftAligned ? 0 : borderThinkness) - (atBeginning && leftCornerWidget ? 1 : 0));
                painter->drawPoint(x1 + 1, y1 + 1);
                painter->setPen(dark);
                painter->drawLine(x1, y1 + 2, x1, y2 - ((onlyOne || atBeginning)  && leftAligned ? 0 : borderThinkness) - (atBeginning && leftCornerWidget ? 1 : 0));
            }
            // Top
            {
                int beg = x1 + (previousSelected ? 0 : 2);
                int end = x2 - (nextSelected ? 0 : 2);
                painter->setPen(light);

                if (!selected)painter->drawLine(beg - 2, y1 + 1, end, y1 + 1);

                if (selected)
                    painter->setPen(QPen(activeHighlight.darker(150), 0));
                else
                    painter->setPen(darkOutline);
                painter->drawLine(beg, y1 , end, y1);

                if (atBeginning|| selected) {
                    painter->drawPoint(beg - 1, y1 + 1);
                } else if (!atBeginning) {
                    painter->drawPoint(beg - 1, y1);
                    painter->drawPoint(beg - 2, y1);
                    if (!lastTab) {
                        painter->setPen(dark.lighter(130));
                        painter->drawPoint(end + 1, y1);
                        painter->drawPoint(end + 2 , y1);
                        painter->drawPoint(end + 2, y1 + 1);
                    }
                }
            }
            // Right
            if (lastTab || selected || onlyOne || !nextSelected) {
                painter->setPen(darkOutline);
                painter->drawLine(x2, y1 + 2, x2, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
                if (selected)
                    painter->setPen(QPen(activeHighlight.darker(150), 0));
                else
                    painter->setPen(darkOutline);
                painter->drawPoint(x2 - 1, y1 + 1);

                if (selected) {
                    painter->setPen(background.darker(110));
                    painter->drawLine(x2 - 1, y1 + 3, x2 - 1, y2 - ((onlyOne || lastTab) && selected && rightAligned ? 0 : borderThinkness));
                }
            }
        }
        painter->restore();
        break;

#endif // QT_NO_TABBAR
    default:
        QWindowsStyle::drawControl(element,option,painter,widget);
        break;
    }
}

/*!
  \reimp
*/
QPalette QCleanlooksStyle::standardPalette () const
{
    QPalette palette = QWindowsStyle::standardPalette();
    palette.setBrush(QPalette::Active, QPalette::Highlight, QColor(98, 140, 178));
    palette.setBrush(QPalette::Inactive, QPalette::Highlight, QColor(145, 141, 126));
    palette.setBrush(QPalette::Disabled, QPalette::Highlight, QColor(145, 141, 126));

    QColor backGround(239, 235, 231);

    QColor light = backGround.lighter(150);
    QColor base = Qt::white;
    QColor dark = QColor(170, 156, 143).darker(110);
    dark = backGround.darker(150);
    QColor darkDisabled = QColor(209, 200, 191).darker(110);

    //### Find the correct disabled text color
    palette.setBrush(QPalette::Disabled, QPalette::Text, QColor(190, 190, 190));

    palette.setBrush(QPalette::Window, backGround);
    palette.setBrush(QPalette::Mid, backGround.darker(130));
    palette.setBrush(QPalette::Light, light);

    palette.setBrush(QPalette::Active, QPalette::Base, base);
    palette.setBrush(QPalette::Inactive, QPalette::Base, base);
    palette.setBrush(QPalette::Disabled, QPalette::Base, backGround);

    palette.setBrush(QPalette::Midlight, palette.mid().color().lighter(110));

    palette.setBrush(QPalette::All, QPalette::Dark, dark);
    palette.setBrush(QPalette::Disabled, QPalette::Dark, darkDisabled);

    QColor button = backGround;

    palette.setBrush(QPalette::Button, button);

    QColor shadow = dark.darker(135);
    palette.setBrush(QPalette::Shadow, shadow);
    palette.setBrush(QPalette::Disabled, QPalette::Shadow, shadow.lighter(150));
    palette.setBrush(QPalette::HighlightedText, QColor(QRgb(0xffffffff)));
    return palette;
}

/*!
  \reimp
*/
void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
                                         QPainter *painter, const QWidget *widget) const
{
    QColor button = option->palette.button().color();
    QColor dark;
    QColor grooveColor;
    QColor darkOutline;
    dark.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*1.9)),
                qMin(255, (int)(button.value()*0.7)));
    grooveColor.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*2.6)),
                qMin(255, (int)(button.value()*0.9)));
    darkOutline.setHsv(button.hue(),
                qMin(255, (int)(button.saturation()*3.0)),
                qMin(255, (int)(button.value()*0.6)));

    QColor alphaCornerColor;
    if (widget) {
        // ### backgroundrole/foregroundrole should be part of the style option
        alphaCornerColor = mergedColors(option->palette.color(widget->backgroundRole()), darkOutline);
    } else {
        alphaCornerColor = mergedColors(option->palette.background().color(), darkOutline);
    }
    QColor gripShadow = grooveColor.darker(110);
    QColor buttonShadow = option->palette.button().color().darker(110);

    QColor gradientStartColor = option->palette.button().color().lighter(108);
    QColor gradientStopColor = mergedColors(option->palette.button().color().darker(108), dark.lighter(150), 70);

    QPalette palette = option->palette;

    switch (control) {
#ifndef QT_NO_SPINBOX
    case CC_SpinBox:
        if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
            QPixmap cache;
            QString pixmapName = QStyleHelper::uniqueName(QLatin1String("spinbox"), spinBox, spinBox->rect.size());
            if (!QPixmapCache::find(pixmapName, cache)) {
                cache = QPixmap(spinBox->rect.size());
                cache.fill(Qt::transparent);
                QRect pixmapRect(0, 0, spinBox->rect.width(), spinBox->rect.height());
                QPainter cachePainter(&cache);

                bool isEnabled = (spinBox->state & State_Enabled);
                //bool focus = isEnabled && (spinBox->state & State_HasFocus);
                bool hover = isEnabled && (spinBox->state & State_MouseOver);
                bool sunken = (spinBox->state & State_Sunken);
                bool upIsActive = (spinBox->activeSubControls == SC_SpinBoxUp);
                bool downIsActive = (spinBox->activeSubControls == SC_SpinBoxDown);

                QRect rect = pixmapRect;
                QStyleOptionSpinBox spinBoxCopy = *spinBox;
                spinBoxCopy.rect = pixmapRect;
                QRect upRect = proxy()->subControlRect(CC_SpinBox, &spinBoxCopy, SC_SpinBoxUp, widget);
                QRect downRect = proxy()->subControlRect(CC_SpinBox, &spinBoxCopy, SC_SpinBoxDown, widget);

                int fw = spinBoxCopy.frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, &spinBoxCopy, widget) : 0;
                cachePainter.fillRect(rect.adjusted(1, qMax(fw - 1, 0), -1, -fw),
                                      option->palette.base());

                QRect r = rect.adjusted(0, 1, 0, -1);
                if (spinBox->frame) {

                    QColor topShadow = darkOutline;
                    topShadow.setAlpha(60);
                    cachePainter.setPen(topShadow);

                    // antialias corners
                    const QPoint points[8] = {
                        QPoint(r.right(), r.top() + 1),
                        QPoint(r.right() - 1, r.top() ),
                        QPoint(r.right(), r.bottom() - 1),
                        QPoint(r.right() - 1, r.bottom() ),
                        QPoint(r.left() + 1, r.bottom()),
                        QPoint(r.left(), r.bottom() - 1),
                        QPoint(r.left() + 1, r.top()),
                        QPoint(r.left(), r.top() + 1)
                    };
                    cachePainter.drawPoints(points, 8);

                    // draw frame
                    topShadow.setAlpha(30);
                    cachePainter.setPen(topShadow);
                    cachePainter.drawLine(QPoint(r.left() + 2, r.top() - 1), QPoint(r.right() - 2, r.top() - 1));

                    cachePainter.setPen(QPen(option->palette.background().color(), 1));
                    cachePainter.drawLine(QPoint(r.left() + 2, r.top() + 1), QPoint(r.right() - 2, r.top() + 1));
                    QColor highlight = Qt::white;
                    highlight.setAlpha(130);
                    cachePainter.setPen(option->palette.base().color().darker(120));
                    cachePainter.drawLine(QPoint(r.left() + 1, r.top() + 1),
                                  QPoint(r.right() - 1, r.top() + 1));
                    cachePainter.drawLine(QPoint(r.left() + 1, r.top() + 1),
                                  QPoint(r.left() + 1, r.bottom() - 1));
                    cachePainter.setPen(option->palette.base().color());
                    cachePainter.drawLine(QPoint(r.right() - 1, r.top() + 1),
                                  QPoint(r.right() - 1, r.bottom() - 1));
                    cachePainter.drawLine(QPoint(r.left() + 1, r.bottom() - 1),
                                  QPoint(r.right() - 1, r.bottom() - 1));
                    cachePainter.setPen(highlight);
                    cachePainter.drawLine(QPoint(r.left() + 3, r.bottom() + 1),
                                  QPoint(r.right() - 3, r.bottom() + 1));

                    cachePainter.setPen(QPen(darkOutline, 1));

                    // top and bottom lines
                    const QLine lines[4] = {
                        QLine(QPoint(r.left() + 2, r.bottom()), QPoint(r.right()- 2, r.bottom())),
                        QLine(QPoint(r.left() + 2, r.top()), QPoint(r.right() - 2, r.top())),
                        QLine(QPoint(r.right(), r.top() + 2), QPoint(r.right(), r.bottom() - 2)),
                        QLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2))
                    };
                    cachePainter.drawLines(lines, 4);
                }

                    // gradients
                    qt_cleanlooks_draw_gradient(&cachePainter, upRect,
                                            gradientStartColor.darker(106),
                                            gradientStopColor, TopDown, option->palette.button());
                    qt_cleanlooks_draw_gradient(&cachePainter, downRect.adjusted(0, 0, 0, 1),
                                            gradientStartColor.darker(106),
                                            gradientStopColor, TopDown, option->palette.button());
                if (isEnabled) {
                    if(upIsActive) {
                        if (sunken) {
                            cachePainter.fillRect(upRect.adjusted(1, 0, 0, 0), gradientStopColor.darker(110));
                        } else if (hover) {
                            qt_cleanlooks_draw_gradient(&cachePainter, upRect.adjusted(1, 0, 0, 0),
                                                    gradientStartColor.lighter(110),
                                                    gradientStopColor.lighter(110), TopDown, option->palette.button());
                        }
                    }
                    if(downIsActive) {
                        if (sunken) {
                            cachePainter.fillRect(downRect.adjusted(1, 0, 0, 1), gradientStopColor.darker(110));

                        } else if (hover) {
                                qt_cleanlooks_draw_gradient(&cachePainter, downRect.adjusted(1, 0, 0, 1),
                                                        gradientStartColor.lighter(110),
                                                        gradientStopColor.lighter(110), TopDown, option->palette.button());
                        }
                    }
                }

                if (spinBox->frame) {
                    // rounded corners
                    const QPoint points[4] = {
                        QPoint(r.left() + 1, r.bottom() - 1),
                        QPoint(r.left() + 1, r.top() + 1),
                        QPoint(r.right() - 1, r.bottom() - 1),
                        QPoint(r.right() - 1, r.top() + 1)
                    };
                    cachePainter.drawPoints(points, 4);

                    if (option->state & State_HasFocus) {
                        QColor darkoutline = option->palette.highlight().color().darker(150);
                        QColor innerline = mergedColors(option->palette.highlight().color(), Qt::white);
                        cachePainter.setPen(QPen(innerline, 0));
                        if (spinBox->direction == Qt::LeftToRight) {
                            cachePainter.drawRect(rect.adjusted(1, 2, -3 -downRect.width(), -3));
                            cachePainter.setPen(QPen(darkoutline, 0));
                            const QLine lines[4] = {
                                QLine(QPoint(r.left() + 2, r.bottom()), QPoint(r.right()- downRect.width() - 1, r.bottom())),
                                QLine(QPoint(r.left() + 2, r.top()), QPoint(r.right() - downRect.width() - 1, r.top())),
                                QLine(QPoint(r.right() - downRect.width() - 1, r.top() + 1), QPoint(r.right()- downRect.width() - 1, r.bottom() - 1)),
                                QLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2))
                            };
                            cachePainter.drawLines(lines, 4);
                            cachePainter.drawPoint(QPoint(r.left() + 1, r.bottom() - 1));
                            cachePainter.drawPoint(QPoint(r.left() + 1, r.top() + 1));
                            cachePainter.drawLine(QPoint(r.left(), r.top() + 2), QPoint(r.left(), r.bottom() - 2));
                        } else {
                            cachePainter.drawRect(rect.adjusted(downRect.width() + 2, 2, -2, -3));
                            cachePainter.setPen(QPen(darkoutline, 0));
                            cachePainter.drawLine(QPoint(r.left() + downRect.width(), r.bottom()), QPoint(r.right()- 2 - 1, r.bottom()));
                            cachePainter.drawLine(QPoint(r.left() + downRect.width(), r.top()), QPoint(r.right() - 2 - 1, r.top()));

                            cachePainter.drawLine(QPoint(r.right(), r.top() + 2), QPoint(r.right(), r.bottom() - 2));
                            cachePainter.drawPoint(QPoint(r.right() - 1, r.bottom() - 1));
                            cachePainter.drawPoint(QPoint(r.right() - 1, r.top() + 1));
                            cachePainter.drawLine(QPoint(r.left() + downRect.width() + 1, r.top()),
                                                  QPoint(r.left() + downRect.width() + 1, r.bottom()));
                        }
                    }
                }

                // outline the up/down buttons
                cachePainter.setPen(darkOutline);
                QColor light = option->palette.light().color().lighter();

                if (spinBox->direction == Qt::RightToLeft) {
                    cachePainter.drawLine(upRect.right(), upRect.top() - 1, upRect.right(), downRect.bottom() + 1);
                    cachePainter.setPen(light);
                    cachePainter.drawLine(upRect.right() - 1, upRect.top() + 3, upRect.right() - 1, downRect.bottom() );
                } else {
                    cachePainter.drawLine(upRect.left(), upRect.top() - 1, upRect.left(), downRect.bottom() + 1);
                    cachePainter.setPen(light);
                    cachePainter.drawLine(upRect.left() + 1, upRect.top() , upRect.left() + 1, downRect.bottom() );
                }
                if (upIsActive && sunken) {
                    cachePainter.setPen(gradientStopColor.darker(130));
                    cachePainter.drawLine(upRect.left() + 1, upRect.top(), upRect.left() + 1, upRect.bottom());
                    cachePainter.drawLine(upRect.left(), upRect.top() - 1, upRect.right(), upRect.top() - 1);
                } else {
                    cachePainter.setPen(light);
                    cachePainter.drawLine(upRect.topLeft() + QPoint(1, -1), upRect.topRight() + QPoint(-1, -1));
                    cachePainter.setPen(darkOutline);
                    cachePainter.drawLine(upRect.bottomLeft(), upRect.bottomRight());
                }
                if (downIsActive && sunken) {
                    cachePainter.setPen(gradientStopColor.darker(130));
                    cachePainter.drawLine(downRect.left() + 1, downRect.top(), downRect.left() + 1, downRect.bottom() + 1);
                    cachePainter.drawLine(downRect.left(), downRect.top(), downRect.right(), downRect.top());
                    cachePainter.setPen(gradientStopColor.darker(110));
                    cachePainter.drawLine(downRect.left(), downRect.bottom() + 1, downRect.right(), downRect.bottom() + 1);
                } else {
                    cachePainter.setPen(light);
                    cachePainter.drawLine(downRect.topLeft() + QPoint(2,0), downRect.topRight());
                }

                if (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) {
                    int centerX = upRect.center().x();
                    int centerY = upRect.center().y();
                    cachePainter.setPen(spinBox->palette.foreground().color());

                    // plus/minus
                    if (spinBox->activeSubControls == SC_SpinBoxUp && sunken) {
                        cachePainter.drawLine(1 + centerX - 2, 1 + centerY, 1 + centerX + 2, 1 + centerY);
                        cachePainter.drawLine(1 + centerX, 1 + centerY - 2, 1 + centerX, 1 + centerY + 2);
                    } else {
                        cachePainter.drawLine(centerX - 2, centerY, centerX + 2, centerY);
                        cachePainter.drawLine(centerX, centerY - 2, centerX, centerY + 2);
                    }

                    centerX = downRect.center().x();
                    centerY = downRect.center().y();
                    if (spinBox->activeSubControls == SC_SpinBoxDown && sunken) {
                        cachePainter.drawLine(1 + centerX - 2, 1 + centerY, 1 + centerX + 2, 1 + centerY);
                    } else {
                        cachePainter.drawLine(centerX - 2, centerY, centerX + 2, centerY);
                    }
                } else if (spinBox->buttonSymbols == QAbstractSpinBox::UpDownArrows){
                    // arrows
                    QImage upArrow(qt_spinbox_button_arrow_up);
                    upArrow.setColor(1, spinBox->palette.foreground().color().rgba());

                    cachePainter.drawImage(upRect.center().x() - upArrow.width() / 2,
                                            upRect.center().y() - upArrow.height() / 2,
                                            upArrow);

                    QImage downArrow(qt_spinbox_button_arrow_down);
                    downArrow.setColor(1, spinBox->palette.foreground().color().rgba());

                    cachePainter.drawImage(downRect.center().x() - downArrow.width() / 2,
                                            downRect.center().y() - downArrow.height() / 2 + 1,
                                            downArrow);
                }

                QColor disabledColor = option->palette.background().color();
                disabledColor.setAlpha(150);
                if (!(spinBox->stepEnabled & QAbstractSpinBox::StepUpEnabled))
                    cachePainter.fillRect(upRect.adjusted(1, 0, 0, 0), disabledColor);
                if (!(spinBox->stepEnabled & QAbstractSpinBox::StepDownEnabled)) {
                    cachePainter.fillRect(downRect.adjusted(1, 0, 0, 0), disabledColor);
                }
                cachePainter.end();
                QPixmapCache::insert(pixmapName, cache);
            }
            painter->drawPixmap(spinBox->rect.topLeft(), cache);
        }
        break;
#endif // QT_NO_SPINBOX
    case CC_TitleBar:
        painter->save();
        if (const QStyleOptionTitleBar *titleBar = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
            const int buttonMargin = 5;
            bool active = (titleBar->titleBarState & State_Active);
            QRect fullRect = titleBar->rect;
            QPalette palette = option->palette;
            QColor highlight = option->palette.highlight().color();

            QColor titleBarFrameBorder(active ? highlight.darker(180): dark.darker(110));
            QColor titleBarHighlight(active ? highlight.lighter(120): palette.background().color().lighter(120));
            QColor textColor(active ? 0xffffff : 0xff000000);
            QColor textAlphaColor(active ? 0xffffff : 0xff000000 );

#ifdef  QT3_SUPPORT
            if (widget && widget->inherits("Q3DockWindowTitleBar")) {
                QStyleOptionDockWidgetV2 dockwidget;
                dockwidget.QStyleOption::operator=(*option);
                proxy()->drawControl(CE_DockWidgetTitle, &dockwidget, painter, widget);
            } else
#endif // QT3_SUPPORT
            {
                // Fill title bar gradient
                QColor titlebarColor = QColor(active ? highlight: palette.background().color());
                QLinearGradient gradient(option->rect.center().x(), option->rect.top(),
                                         option->rect.center().x(), option->rect.bottom());

                gradient.setColorAt(0, titlebarColor.lighter(114));
                gradient.setColorAt(0.5, titlebarColor.lighter(102));
                gradient.setColorAt(0.51, titlebarColor.darker(104));
                gradient.setColorAt(1, titlebarColor);
                painter->fillRect(option->rect.adjusted(1, 1, -1, 0), gradient);

                // Frame and rounded corners
                painter->setPen(titleBarFrameBorder);

                // top outline
                painter->drawLine(fullRect.left() + 5, fullRect.top(), fullRect.right() - 5, fullRect.top());
                painter->drawLine(fullRect.left(), fullRect.top() + 4, fullRect.left(), fullRect.bottom());
                const QPoint points[5] = {
                    QPoint(fullRect.left() + 4, fullRect.top() + 1),
                    QPoint(fullRect.left() + 3, fullRect.top() + 1),
                    QPoint(fullRect.left() + 2, fullRect.top() + 2),
                    QPoint(fullRect.left() + 1, fullRect.top() + 3),
                    QPoint(fullRect.left() + 1, fullRect.top() + 4)
                };
                painter->drawPoints(points, 5);

                painter->drawLine(fullRect.right(), fullRect.top() + 4, fullRect.right(), fullRect.bottom());
                const QPoint points2[5] = {
                    QPoint(fullRect.right() - 3, fullRect.top() + 1),
                    QPoint(fullRect.right() - 4, fullRect.top() + 1),
                    QPoint(fullRect.right() - 2, fullRect.top() + 2),
                    QPoint(fullRect.right() - 1, fullRect.top() + 3),
                    QPoint(fullRect.right() - 1, fullRect.top() + 4)
                };
                painter->drawPoints(points2, 5);

                // draw bottomline
                painter->drawLine(fullRect.right(), fullRect.bottom(), fullRect.left(), fullRect.bottom());

                // top highlight
                painter->setPen(titleBarHighlight);
                painter->drawLine(fullRect.left() + 6, fullRect.top() + 1, fullRect.right() - 6, fullRect.top() + 1);
            }
            // draw title
            QRect textRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarLabel, widget);
            QFont font = painter->font();
            font.setBold(true);
            painter->setFont(font);
            painter->setPen(active? (titleBar->palette.text().color().lighter(120)) :
                                     titleBar->palette.text().color() );
            // Note workspace also does elliding but it does not use the correct font
            QString title = QFontMetrics(font).elidedText(titleBar->text, Qt::ElideRight, textRect.width() - 14);
            painter->drawText(textRect.adjusted(1, 1, 1, 1), title, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
            painter->setPen(Qt::white);
            if (active)
                painter->drawText(textRect, title, QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
            // min button
            if ((titleBar->subControls & SC_TitleBarMinButton) && (titleBar->titleBarFlags & Qt::WindowMinimizeButtonHint) &&
                !(titleBar->titleBarState& Qt::WindowMinimized)) {
                QRect minButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarMinButton, widget);
                if (minButtonRect.isValid()) {
                    bool hover = (titleBar->activeSubControls & SC_TitleBarMinButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarMinButton) && (titleBar->state & State_Sunken);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, minButtonRect, hover, sunken);
                    QRect minButtonIconRect = minButtonRect.adjusted(buttonMargin ,buttonMargin , -buttonMargin, -buttonMargin);
                    painter->setPen(textColor);
                    painter->drawLine(minButtonIconRect.center().x() - 2, minButtonIconRect.center().y() + 3,
                                    minButtonIconRect.center().x() + 3, minButtonIconRect.center().y() + 3);
                    painter->drawLine(minButtonIconRect.center().x() - 2, minButtonIconRect.center().y() + 4,
                                    minButtonIconRect.center().x() + 3, minButtonIconRect.center().y() + 4);
                    painter->setPen(textAlphaColor);
                    painter->drawLine(minButtonIconRect.center().x() - 3, minButtonIconRect.center().y() + 3,
                                    minButtonIconRect.center().x() - 3, minButtonIconRect.center().y() + 4);
                    painter->drawLine(minButtonIconRect.center().x() + 4, minButtonIconRect.center().y() + 3,
                                    minButtonIconRect.center().x() + 4, minButtonIconRect.center().y() + 4);
                }
            }
            // max button
            if ((titleBar->subControls & SC_TitleBarMaxButton) && (titleBar->titleBarFlags & Qt::WindowMaximizeButtonHint) &&
                !(titleBar->titleBarState & Qt::WindowMaximized)) {
                QRect maxButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarMaxButton, widget);
                if (maxButtonRect.isValid()) {
                    bool hover = (titleBar->activeSubControls & SC_TitleBarMaxButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarMaxButton) && (titleBar->state & State_Sunken);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, maxButtonRect, hover, sunken);

                    QRect maxButtonIconRect = maxButtonRect.adjusted(buttonMargin, buttonMargin, -buttonMargin, -buttonMargin);

                    painter->setPen(textColor);
                    painter->drawRect(maxButtonIconRect.adjusted(0, 0, -1, -1));
                    painter->drawLine(maxButtonIconRect.left() + 1, maxButtonIconRect.top() + 1,
                                    maxButtonIconRect.right() - 1, maxButtonIconRect.top() + 1);
                    painter->setPen(textAlphaColor);
                    const QPoint points[4] = {
                        maxButtonIconRect.topLeft(),
                        maxButtonIconRect.topRight(),
                        maxButtonIconRect.bottomLeft(),
                        maxButtonIconRect.bottomRight()
                    };
                    painter->drawPoints(points, 4);
                }
            }

            // close button
            if ((titleBar->subControls & SC_TitleBarCloseButton) && (titleBar->titleBarFlags & Qt::WindowSystemMenuHint)) {
                QRect closeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarCloseButton, widget);
                if (closeButtonRect.isValid()) {
                    bool hover = (titleBar->activeSubControls & SC_TitleBarCloseButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarCloseButton) && (titleBar->state & State_Sunken);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, closeButtonRect, hover, sunken);
                    QRect closeIconRect = closeButtonRect.adjusted(buttonMargin, buttonMargin, -buttonMargin, -buttonMargin);
                    painter->setPen(textAlphaColor);
                    const QLine lines[4] = {
                        QLine(closeIconRect.left() + 1, closeIconRect.top(),
                              closeIconRect.right(), closeIconRect.bottom() - 1),
                        QLine(closeIconRect.left(), closeIconRect.top() + 1,
                              closeIconRect.right() - 1, closeIconRect.bottom()),
                        QLine(closeIconRect.right() - 1, closeIconRect.top(),
                              closeIconRect.left(), closeIconRect.bottom() - 1),
                        QLine(closeIconRect.right(), closeIconRect.top() + 1,
                              closeIconRect.left() + 1, closeIconRect.bottom())
                    };
                    painter->drawLines(lines, 4);
                    const QPoint points[4] = {
                        closeIconRect.topLeft(),
                        closeIconRect.topRight(),
                        closeIconRect.bottomLeft(),
                        closeIconRect.bottomRight()
                    };
                    painter->drawPoints(points, 4);

                    painter->setPen(textColor);
                    painter->drawLine(closeIconRect.left() + 1, closeIconRect.top() + 1,
                                    closeIconRect.right() - 1, closeIconRect.bottom() - 1);
                    painter->drawLine(closeIconRect.left() + 1, closeIconRect.bottom() - 1,
                                    closeIconRect.right() - 1, closeIconRect.top() + 1);
                }
            }

            // normalize button
            if ((titleBar->subControls & SC_TitleBarNormalButton) &&
               (((titleBar->titleBarFlags & Qt::WindowMinimizeButtonHint) &&
               (titleBar->titleBarState & Qt::WindowMinimized)) ||
               ((titleBar->titleBarFlags & Qt::WindowMaximizeButtonHint) &&
               (titleBar->titleBarState & Qt::WindowMaximized)))) {
                QRect normalButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarNormalButton, widget);
                if (normalButtonRect.isValid()) {

                    bool hover = (titleBar->activeSubControls & SC_TitleBarNormalButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarNormalButton) && (titleBar->state & State_Sunken);
                    QRect normalButtonIconRect = normalButtonRect.adjusted(buttonMargin, buttonMargin, -buttonMargin, -buttonMargin);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, normalButtonRect, hover, sunken);

                    QRect frontWindowRect = normalButtonIconRect.adjusted(0, 3, -3, 0);
                    painter->setPen(textColor);
                    painter->drawRect(frontWindowRect.adjusted(0, 0, -1, -1));
                    painter->drawLine(frontWindowRect.left() + 1, frontWindowRect.top() + 1,
                                    frontWindowRect.right() - 1, frontWindowRect.top() + 1);
                    painter->setPen(textAlphaColor);
                    const QPoint points[4] = {
                        frontWindowRect.topLeft(),
                        frontWindowRect.topRight(),
                        frontWindowRect.bottomLeft(),
                        frontWindowRect.bottomRight()
                    };
                    painter->drawPoints(points, 4);

                    QRect backWindowRect = normalButtonIconRect.adjusted(3, 0, 0, -3);
                    QRegion clipRegion = backWindowRect;
                    clipRegion -= frontWindowRect;
                    painter->save();
                    painter->setClipRegion(clipRegion);
                    painter->setPen(textColor);
                    painter->drawRect(backWindowRect.adjusted(0, 0, -1, -1));
                    painter->drawLine(backWindowRect.left() + 1, backWindowRect.top() + 1,
                                    backWindowRect.right() - 1, backWindowRect.top() + 1);
                    painter->setPen(textAlphaColor);
                    const QPoint points2[4] = {
                        backWindowRect.topLeft(),
                        backWindowRect.topRight(),
                        backWindowRect.bottomLeft(),
                        backWindowRect.bottomRight()
                    };
                    painter->drawPoints(points2, 4);
                    painter->restore();
                }
            }

            // context help button
            if (titleBar->subControls & SC_TitleBarContextHelpButton
                && (titleBar->titleBarFlags & Qt::WindowContextHelpButtonHint)) {
                QRect contextHelpButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarContextHelpButton, widget);
                if (contextHelpButtonRect.isValid()) {
                    bool hover = (titleBar->activeSubControls & SC_TitleBarContextHelpButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarContextHelpButton) && (titleBar->state & State_Sunken);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, contextHelpButtonRect, hover, sunken);

                    QColor blend;
                    QImage image(qt_titlebar_context_help);
                    QColor alpha = textColor;
                    alpha.setAlpha(128);
                    image.setColor(1, textColor.rgba());
                    image.setColor(2, alpha.rgba());
                    painter->setRenderHint(QPainter::SmoothPixmapTransform);
                    painter->drawImage(contextHelpButtonRect.adjusted(4, 4, -4, -4), image);
                }
            }

            // shade button
            if (titleBar->subControls & SC_TitleBarShadeButton && (titleBar->titleBarFlags & Qt::WindowShadeButtonHint)) {
                QRect shadeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarShadeButton, widget);
                if (shadeButtonRect.isValid()) {
                    bool hover = (titleBar->activeSubControls & SC_TitleBarShadeButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarShadeButton) && (titleBar->state & State_Sunken);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, shadeButtonRect, hover, sunken);
                    QImage image(qt_scrollbar_button_arrow_up);
                    image.setColor(1, textColor.rgba());
                    painter->drawImage(shadeButtonRect.adjusted(5, 7, -5, -7), image);
                }
            }

            // unshade button
            if (titleBar->subControls & SC_TitleBarUnshadeButton && (titleBar->titleBarFlags & Qt::WindowShadeButtonHint)) {
                QRect unshadeButtonRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarUnshadeButton, widget);
                if (unshadeButtonRect.isValid()) {
                    bool hover = (titleBar->activeSubControls & SC_TitleBarUnshadeButton) && (titleBar->state & State_MouseOver);
                    bool sunken = (titleBar->activeSubControls & SC_TitleBarUnshadeButton) && (titleBar->state & State_Sunken);
                    qt_cleanlooks_draw_mdibutton(painter, titleBar, unshadeButtonRect, hover, sunken);
                    QImage image(qt_scrollbar_button_arrow_down);
                    image.setColor(1, textColor.rgba());
                    painter->drawImage(unshadeButtonRect.adjusted(5, 7, -5, -7), image);
                }
            }

            if ((titleBar->subControls & SC_TitleBarSysMenu) && (titleBar->titleBarFlags & Qt::WindowSystemMenuHint)) {
                QRect iconRect = proxy()->subControlRect(CC_TitleBar, titleBar, SC_TitleBarSysMenu, widget);
                if (iconRect.isValid()) {
                    if (!titleBar->icon.isNull()) {
                        titleBar->icon.paint(painter, iconRect);
                    } else {
                        QStyleOption tool(0);
                        tool.palette = titleBar->palette;
                        QPixmap pm = standardIcon(SP_TitleBarMenuButton, &tool, widget).pixmap(16, 16);
                        tool.rect = iconRect;
                        painter->save();
                        proxy()->drawItemPixmap(painter, iconRect, Qt::AlignCenter, pm);
                        painter->restore();
                    }
                }
            }
        }
        painter->restore();
        break;
#ifndef QT_NO_SCROLLBAR
    case CC_ScrollBar:
        painter->save();
        if (const QStyleOptionSlider *scrollBar = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
            bool isEnabled = scrollBar->state & State_Enabled;
            bool reverse = scrollBar->direction == Qt::RightToLeft;
            bool horizontal = scrollBar->orientation == Qt::Horizontal;
            bool sunken = scrollBar->state & State_Sunken;

            painter->fillRect(option->rect, option->palette.background());

            QRect scrollBarSubLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSubLine, widget);
            QRect scrollBarAddLine = proxy()->subControlRect(control, scrollBar, SC_ScrollBarAddLine, widget);
            QRect scrollBarSlider = proxy()->subControlRect(control, scrollBar, SC_ScrollBarSlider, widget);
            QRect grooveRect = proxy()->subControlRect(control, scrollBar, SC_ScrollBarGroove, widget);

            // paint groove
            if (scrollBar->subControls & SC_ScrollBarGroove) {
                painter->setBrush(grooveColor);
                painter->setPen(Qt::NoPen);
                if (horizontal) {
                    painter->drawRect(grooveRect);
                    painter->setPen(darkOutline);
                    painter->drawLine(grooveRect.topLeft(), grooveRect.topRight());
                    painter->drawLine(grooveRect.bottomLeft(), grooveRect.bottomRight());
                } else {
                    painter->drawRect(grooveRect);
                    painter->setPen(darkOutline);
                    painter->drawLine(grooveRect.topLeft(), grooveRect.bottomLeft());
                    painter->drawLine(grooveRect.topRight(), grooveRect.bottomRight());
                }
            }
            //paint slider
            if (scrollBar->subControls & SC_ScrollBarSlider) {
                QRect pixmapRect = scrollBarSlider;
                if (horizontal)
                    pixmapRect.adjust(-1, 0, 0, -1);
                else
                    pixmapRect.adjust(0, -1, -1, 0);

                if (isEnabled) {
                    QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top(),
                                             pixmapRect.center().x(), pixmapRect.bottom());
                    if (!horizontal)
                        gradient = QLinearGradient(pixmapRect.left(), pixmapRect.center().y(),
                                                   pixmapRect.right(), pixmapRect.center().y());

                    if (option->palette.button().gradient()) {
                        gradient.setStops(option->palette.button().gradient()->stops());
                    } else {
                        if (sunken || (option->state & State_MouseOver &&
                            (scrollBar->activeSubControls & SC_ScrollBarSlider))) {
                            gradient.setColorAt(0, gradientStartColor.lighter(110));
                            gradient.setColorAt(1, gradientStopColor.lighter(110));
                        } else {
                            gradient.setColorAt(0, gradientStartColor);
                            gradient.setColorAt(1, gradientStopColor);
                        }
                    }
                    painter->setPen(QPen(darkOutline, 0));
                    painter->setBrush(gradient);
                    painter->drawRect(pixmapRect);


                    //calculate offsets used by highlight and shadow
                    int yoffset, xoffset;
                    if (option->state & State_Horizontal) {
                        xoffset = 0;
                        yoffset = 1;
                    } else {
                        xoffset = 1;
                        yoffset = 0;
                    }
                    //draw slider highlights
                    painter->setPen(QPen(gradientStopColor, 0));
                    painter->drawLine(scrollBarSlider.left() + xoffset,
                                      scrollBarSlider.bottom() - yoffset,
                                      scrollBarSlider.right() - xoffset,
                                      scrollBarSlider.bottom() - yoffset);
                    painter->drawLine(scrollBarSlider.right() - xoffset,
                                      scrollBarSlider.top() + yoffset,
                                      scrollBarSlider.right() - xoffset,
                                      scrollBarSlider.bottom() - yoffset);

                    //draw slider shadow
                    painter->setPen(QPen(gradientStartColor, 0));
                    painter->drawLine(scrollBarSlider.left() + xoffset,
                                      scrollBarSlider.top() + yoffset,
                                      scrollBarSlider.right() - xoffset,
                                      scrollBarSlider.top() + yoffset);
                    painter->drawLine(scrollBarSlider.left() + xoffset,
                                      scrollBarSlider.top() + yoffset,
                                      scrollBarSlider.left() + xoffset,
                                      scrollBarSlider.bottom() - yoffset);
                } else {
                    QLinearGradient gradient(pixmapRect.center().x(), pixmapRect.top(),
                                             pixmapRect.center().x(), pixmapRect.bottom());
                    if (!horizontal) {
                        gradient = QLinearGradient(pixmapRect.left(), pixmapRect.center().y(),
                                                   pixmapRect.right(), pixmapRect.center().y());
                    }
                    if (sunken) {
                        gradient.setColorAt(0, gradientStartColor.lighter(110));
                        gradient.setColorAt(1, gradientStopColor.lighter(110));
                    } else {
                        gradient.setColorAt(0, gradientStartColor);
                        gradient.setColorAt(1, gradientStopColor);
                    }
                    painter->setPen(darkOutline);
                    painter->setBrush(gradient);
                    painter->drawRect(pixmapRect);
                }
                int gripMargin = 4;
                //draw grips
                if (horizontal) {
                    for (int i = -3; i< 6 ; i += 3) {
                        painter->setPen(QPen(gripShadow, 1));
                        painter->drawLine(
                            QPoint(scrollBarSlider.center().x() + i ,
                                   scrollBarSlider.top() + gripMargin),
                            QPoint(scrollBarSlider.center().x() + i,
                                   scrollBarSlider.bottom() - gripMargin));
                        painter->setPen(QPen(palette.light(), 1));
                        painter->drawLine(
                            QPoint(scrollBarSlider.center().x() + i + 1,
                                   scrollBarSlider.top() + gripMargin  ),
                            QPoint(scrollBarSlider.center().x() + i + 1,
                                   scrollBarSlider.bottom() - gripMargin));
                    }
                } else {
                    for (int i = -3; i < 6 ; i += 3) {
                        painter->setPen(QPen(gripShadow, 1));
                        painter->drawLine(
                            QPoint(scrollBarSlider.left() + gripMargin ,
                                   scrollBarSlider.center().y()+ i),
                            QPoint(scrollBarSlider.right() - gripMargin,
                                   scrollBarSlider.center().y()+ i));
                        painter->setPen(QPen(palette.light(), 1));
                        painter->drawLine(
                            QPoint(scrollBarSlider.left() + gripMargin,
                                   scrollBarSlider.center().y() + 1 + i),
                            QPoint(scrollBarSlider.right() - gripMargin,
                                   scrollBarSlider.center().y() + 1 + i));
                    }
                }
            }

            // The SubLine (up/left) buttons
            if (scrollBar->subControls & SC_ScrollBarSubLine) {
                //int scrollBarExtent = proxy()->pixelMetric(PM_ScrollBarExtent, option, widget);
                QRect pixmapRect = scrollBarSubLine;
                if (isEnabled ) {
                    QRect fillRect = pixmapRect.adjusted(1, 1, -1, -1);
                    // Gradients
                    if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken) {
                        qt_cleanlooks_draw_gradient(painter,
                                                    QRect(fillRect),
                                                    gradientStopColor.darker(120),
                                                    gradientStopColor.darker(120),
                                                    horizontal ? TopDown : FromLeft, option->palette.button());
                    } else {
                        qt_cleanlooks_draw_gradient(painter,
                                                    QRect(fillRect),
                                                    gradientStartColor.lighter(105),
                                                    gradientStopColor,
                                                    horizontal ? TopDown : FromLeft, option->palette.button());
                    }
                }
                // Details
                QImage subButton;
                if (horizontal) {
                    subButton = QImage(reverse ? qt_scrollbar_button_right : qt_scrollbar_button_left);
                } else {
                    subButton = QImage(qt_scrollbar_button_up);
                }
                subButton.setColor(1, alphaCornerColor.rgba());
                subButton.setColor(2, darkOutline.rgba());
                if ((scrollBar->activeSubControls & SC_ScrollBarSubLine) && sunken) {
                    subButton.setColor(3, gradientStopColor.darker(140).rgba());
                    subButton.setColor(4, gradientStopColor.darker(120).rgba());
                } else {
                    subButton.setColor(3, gradientStartColor.lighter(105).rgba());
                    subButton.setColor(4, gradientStopColor.rgba());
                }
                subButton.setColor(5, scrollBar->palette.text().color().rgba());
                painter->drawImage(pixmapRect, subButton);

                // Arrows
                PrimitiveElement arrow;
                if (option->state & State_Horizontal)
                    arrow = option->direction == Qt::LeftToRight ? PE_IndicatorArrowLeft: PE_IndicatorArrowRight;
                else
                    arrow = PE_IndicatorArrowUp;
                QStyleOption arrowOpt = *option;
                arrowOpt.rect = scrollBarSubLine.adjusted(3, 3, -2, -2);
                proxy()->drawPrimitive(arrow, &arrowOpt, painter, widget);


                // The AddLine (down/right) button
                if (scrollBar->subControls & SC_ScrollBarAddLine) {
                    QString addLinePixmapName = QStyleHelper::uniqueName(QLatin1String("scrollbar_addline"), option, QSize(16, 16));
                    QRect pixmapRect = scrollBarAddLine;
                    if (isEnabled) {
                        QRect fillRect = pixmapRect.adjusted(1, 1, -1, -1);
                        // Gradients
                        if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken) {
                            qt_cleanlooks_draw_gradient(painter,
                                                        fillRect,
                                                        gradientStopColor.darker(120),
                                                        gradientStopColor.darker(120),
                                                        horizontal ? TopDown: FromLeft, option->palette.button());
                        } else {
                            qt_cleanlooks_draw_gradient(painter,
                                                        fillRect,
                                                        gradientStartColor.lighter(105),
                                                        gradientStopColor,
                                                        horizontal ? TopDown : FromLeft, option->palette.button());
                        }
                    }
                    // Details
                    QImage addButton;
                    if (horizontal) {
                        addButton = QImage(reverse ? qt_scrollbar_button_left : qt_scrollbar_button_right);
                    } else {
                        addButton = QImage(qt_scrollbar_button_down);
                    }
                    addButton.setColor(1, alphaCornerColor.rgba());
                    addButton.setColor(2, darkOutline.rgba());
                    if ((scrollBar->activeSubControls & SC_ScrollBarAddLine) && sunken) {
                        addButton.setColor(3, gradientStopColor.darker(140).rgba());
                        addButton.setColor(4, gradientStopColor.darker(120).rgba());
                    } else {
                        addButton.setColor(3, gradientStartColor.lighter(105).rgba());
                        addButton.setColor(4, gradientStopColor.rgba());
                    }
                    addButton.setColor(5, scrollBar->palette.text().color().rgba());
                    painter->drawImage(pixmapRect, addButton);

                    PrimitiveElement arrow;
                    if (option->state & State_Horizontal)
                        arrow = option->direction == Qt::LeftToRight ? PE_IndicatorArrowRight : PE_IndicatorArrowLeft;
                    else
                        arrow = PE_IndicatorArrowDown;

                    QStyleOption arrowOpt = *option;
                    arrowOpt.rect = scrollBarAddLine.adjusted(3, 3, -2, -2);
                    proxy()->drawPrimitive(arrow, &arrowOpt, painter, widget);
                }
            }
        }
        painter->restore();
        break;;
#endif // QT_NO_SCROLLBAR
#ifndef QT_NO_COMBOBOX
    case CC_ComboBox:
        painter->save();
        if (const QStyleOptionComboBox *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
            bool sunken = comboBox->state & State_On; // play dead, if combobox has no items
            bool isEnabled = (comboBox->state & State_Enabled);
            bool focus = isEnabled && (comboBox->state & State_HasFocus);
            QPixmap cache;
            QString pixmapName = QStyleHelper::uniqueName(QLatin1String("combobox"), option, comboBox->rect.size());
            if (sunken)
                pixmapName += QLatin1String("-sunken");
            if (comboBox->editable)
                pixmapName += QLatin1String("-editable");
            if (isEnabled)
                pixmapName += QLatin1String("-enabled");

            if (!QPixmapCache::find(pixmapName, cache)) {
                cache = QPixmap(comboBox->rect.size());
                cache.fill(Qt::transparent);
                QPainter cachePainter(&cache);
                QRect pixmapRect(0, 0, comboBox->rect.width(), comboBox->rect.height());
                QStyleOptionComboBox comboBoxCopy = *comboBox;
                comboBoxCopy.rect = pixmapRect;

                QRect rect = pixmapRect;
                QRect downArrowRect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy,
                                                     SC_ComboBoxArrow, widget);
                QRect editRect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy,
                                                     SC_ComboBoxEditField, widget);
                // Draw a push button
                if (comboBox->editable) {
                    QStyleOptionFrame  buttonOption;
                    buttonOption.QStyleOption::operator=(*comboBox);
                    buttonOption.rect = rect;
                    buttonOption.state = comboBox->state & (State_Enabled | State_MouseOver);

                    if (sunken) {
                        buttonOption.state |= State_Sunken;
                        buttonOption.state &= ~State_MouseOver;
                    }

                    proxy()->drawPrimitive(PE_PanelButtonCommand, &buttonOption, &cachePainter, widget);

                    //remove shadow from left side of edit field when pressed:
                    if (comboBox->direction != Qt::RightToLeft)
                        cachePainter.fillRect(editRect.left() - 1, editRect.top() + 1, editRect.left(),
                        editRect.bottom() - 3, option->palette.base());

                    cachePainter.setPen(dark.lighter(110));
                    if (!sunken) {
                        int borderSize = 2;
                        if (comboBox->direction == Qt::RightToLeft) {
                            cachePainter.drawLine(QPoint(downArrowRect.right() - 1, downArrowRect.top() + borderSize ),
                                                  QPoint(downArrowRect.right() - 1, downArrowRect.bottom() - borderSize));
                            cachePainter.setPen(option->palette.light().color());
                            cachePainter.drawLine(QPoint(downArrowRect.right(), downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.right(), downArrowRect.bottom() - borderSize));
                        } else {
                            cachePainter.drawLine(QPoint(downArrowRect.left() , downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.left() , downArrowRect.bottom() - borderSize));
                            cachePainter.setPen(option->palette.light().color());
                            cachePainter.drawLine(QPoint(downArrowRect.left() + 1, downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.left() + 1, downArrowRect.bottom() - borderSize));
                        }
                    } else {
                        if (comboBox->direction == Qt::RightToLeft) {
                            cachePainter.drawLine(QPoint(downArrowRect.right(), downArrowRect.top() + 2),
                                                  QPoint(downArrowRect.right(), downArrowRect.bottom() - 2));

                        } else {
                            cachePainter.drawLine(QPoint(downArrowRect.left(), downArrowRect.top() + 2),
                                                  QPoint(downArrowRect.left(), downArrowRect.bottom() - 2));
                        }
                    }
                } else {
                    QStyleOptionButton buttonOption;
                    buttonOption.QStyleOption::operator=(*comboBox);
                    buttonOption.rect = rect;
                    buttonOption.state = comboBox->state & (State_Enabled | State_MouseOver);
                    if (sunken) {
                        buttonOption.state |= State_Sunken;
                        buttonOption.state &= ~State_MouseOver;
                    }
                    proxy()->drawPrimitive(PE_PanelButtonCommand, &buttonOption, &cachePainter, widget);

                    cachePainter.setPen(buttonShadow.darker(102));
                    int borderSize = 4;

                    if (!sunken) {
                        if (comboBox->direction == Qt::RightToLeft) {
                            cachePainter.drawLine(QPoint(downArrowRect.right() + 1, downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.right() + 1, downArrowRect.bottom() - borderSize));
                            cachePainter.setPen(option->palette.light().color());
                            cachePainter.drawLine(QPoint(downArrowRect.right(), downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.right(), downArrowRect.bottom() - borderSize));
                        } else {
                            cachePainter.drawLine(QPoint(downArrowRect.left() - 1, downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.left() - 1, downArrowRect.bottom() - borderSize));
                            cachePainter.setPen(option->palette.light().color());
                            cachePainter.drawLine(QPoint(downArrowRect.left() , downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.left() , downArrowRect.bottom() - borderSize));
                        }
                    } else {
                        cachePainter.setPen(dark.lighter(110));
                        if (comboBox->direction == Qt::RightToLeft) {
                            cachePainter.drawLine(QPoint(downArrowRect.right() + 1, downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.right() + 1, downArrowRect.bottom() - borderSize));

                        } else {
                            cachePainter.drawLine(QPoint(downArrowRect.left() - 1, downArrowRect.top() + borderSize),
                                                  QPoint(downArrowRect.left() - 1, downArrowRect.bottom() - borderSize));
                        }
                    }
                }


                if (comboBox->subControls & SC_ComboBoxArrow) {
                    if (comboBox->editable) {
                        // Draw the down arrow
                        QImage downArrow(qt_cleanlooks_arrow_down_xpm);
                        downArrow.setColor(1, comboBox->palette.foreground().color().rgba());
                        cachePainter.drawImage(downArrowRect.center().x() - downArrow.width() / 2,
                                               downArrowRect.center().y() - downArrow.height() / 2 + 1, downArrow);
                    } else {
                        // Draw the up/down arrow
                        QImage upArrow(qt_scrollbar_button_arrow_up);
                        upArrow.setColor(1, comboBox->palette.foreground().color().rgba());
                        QImage downArrow(qt_scrollbar_button_arrow_down);
                        downArrow.setColor(1, comboBox->palette.foreground().color().rgba());
                        cachePainter.drawImage(downArrowRect.center().x() - downArrow.width() / 2,
                                               downArrowRect.center().y() - upArrow.height() - 1 , upArrow);
                        cachePainter.drawImage(downArrowRect.center().x() - downArrow.width() / 2,
                                               downArrowRect.center().y()  + 2, downArrow);
                    }
                }
                // Draw the focus rect
                if (focus && !comboBox->editable
                    && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget))) {
                    QStyleOptionFocusRect focus;
                    focus.rect = proxy()->subControlRect(CC_ComboBox, &comboBoxCopy, SC_ComboBoxEditField, widget)
                                 .adjusted(0, 2, option->direction == Qt::RightToLeft ? 1 : -1, -2);
                    proxy()->drawPrimitive(PE_FrameFocusRect, &focus, &cachePainter, widget);
                }
                cachePainter.end();
                QPixmapCache::insert(pixmapName, cache);
            }
            painter->drawPixmap(comboBox->rect.topLeft(), cache);
        }
        painter->restore();
        break;
#endif // QT_NO_COMBOBOX
#ifndef QT_NO_GROUPBOX
    case CC_GroupBox:
        painter->save();
        if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
            QRect textRect = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxLabel, widget);
            QRect checkBoxRect = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxCheckBox, widget);
            bool flat = groupBox->features & QStyleOptionFrameV2::Flat;

            if(!flat) {
                if (groupBox->subControls & QStyle::SC_GroupBoxFrame) {
                    QStyleOptionFrameV2 frame;
                    frame.QStyleOption::operator=(*groupBox);
                    frame.features = groupBox->features;
                    frame.lineWidth = groupBox->lineWidth;
                    frame.midLineWidth = groupBox->midLineWidth;
                    frame.rect = proxy()->subControlRect(CC_GroupBox, option, SC_GroupBoxFrame, widget);

                    painter->save();
                    QRegion region(groupBox->rect);
                    bool ltr = groupBox->direction == Qt::LeftToRight;
                    region -= checkBoxRect.united(textRect).adjusted(ltr ? -4 : 0, 0, ltr ? 0 : 4, 0);
                    if (!groupBox->text.isEmpty() ||  groupBox->subControls & SC_GroupBoxCheckBox)
                        painter->setClipRegion(region);
                    frame.palette.setBrush(QPalette::Dark, option->palette.mid().color().lighter(110));
                    proxy()->drawPrimitive(PE_FrameGroupBox, &frame, painter);
                    painter->restore();
                }
            }
            // Draw title
            if ((groupBox->subControls & QStyle::SC_GroupBoxLabel) && !groupBox->text.isEmpty()) {
                if (!groupBox->text.isEmpty()) {
                    QColor textColor = groupBox->textColor;
                    if (textColor.isValid())
                        painter->setPen(textColor);
                    int alignment = int(groupBox->textAlignment);
                    if (!styleHint(QStyle::SH_UnderlineShortcut, option, widget))
                        alignment |= Qt::TextHideMnemonic;
                    if (flat) {
                        QFont font = painter->font();
                        font.setBold(true);
                        painter->setFont(font);
                        if (groupBox->subControls & SC_GroupBoxCheckBox) {
                            textRect.adjust(checkBoxRect.right() + 4, 0, checkBoxRect.right() + 4, 0);
                        }
                    }
                    painter->drawText(textRect, Qt::TextShowMnemonic | Qt::AlignLeft| alignment, groupBox->text);
                }
            }
            if (groupBox->subControls & SC_GroupBoxCheckBox) {
                QStyleOptionButton box;
                box.QStyleOption::operator=(*groupBox);
                box.rect = checkBoxRect;
                proxy()->drawPrimitive(PE_IndicatorCheckBox, &box, painter, widget);
            }
        }
        painter->restore();
        break;
#endif // QT_NO_GROUPBOX
#ifndef QT_NO_SLIDER
    case CC_Slider:
        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
            QRect groove = proxy()->subControlRect(CC_Slider, option, SC_SliderGroove, widget);
            QRect handle = proxy()->subControlRect(CC_Slider, option, SC_SliderHandle, widget);

            bool horizontal = slider->orientation == Qt::Horizontal;
            bool ticksAbove = slider->tickPosition & QSlider::TicksAbove;
            bool ticksBelow = slider->tickPosition & QSlider::TicksBelow;
            QColor activeHighlight = option->palette.color(QPalette::Normal, QPalette::Highlight);
            QPixmap cache;

            QBrush oldBrush = painter->brush();
            QPen oldPen = painter->pen();

            QColor shadowAlpha(Qt::black);
            shadowAlpha.setAlpha(10);
            QColor highlightAlpha(Qt::white);
            highlightAlpha.setAlpha(80);

            if ((option->subControls & SC_SliderGroove) && groove.isValid()) {
                QString groovePixmapName = QStyleHelper::uniqueName(QLatin1String("slider_groove"), option, groove.size());
                QRect pixmapRect(0, 0, groove.width(), groove.height());

                // draw background groove
                if (!QPixmapCache::find(groovePixmapName, cache)) {
                    cache = QPixmap(pixmapRect.size());
                    cache.fill(Qt::transparent);
                    QPainter groovePainter(&cache);

                    groovePainter.setPen(shadowAlpha);
                    groovePainter.drawLine(1, 0, groove.width(), 0);
                    groovePainter.drawLine(0, 0, 0, groove.height() - 1);

                    groovePainter.setPen(highlightAlpha);
                    groovePainter.drawLine(1, groove.height() - 1, groove.width() - 1, groove.height() - 1);
                    groovePainter.drawLine(groove.width() - 1, 1, groove.width() - 1, groove.height() - 1);
                    QLinearGradient gradient;
                    if (horizontal) {
                        gradient.setStart(pixmapRect.center().x(), pixmapRect.top());
                        gradient.setFinalStop(pixmapRect.center().x(), pixmapRect.bottom());
                    }
                    else {
                        gradient.setStart(pixmapRect.left(), pixmapRect.center().y());
                        gradient.setFinalStop(pixmapRect.right(), pixmapRect.center().y());
                    }
                    groovePainter.setPen(QPen(darkOutline.darker(110), 0));
                    gradient.setColorAt(0, grooveColor.darker(110));//dark.lighter(120));
                    gradient.setColorAt(1, grooveColor.lighter(110));//palette.button().color().darker(115));
                    groovePainter.setBrush(gradient);
                    groovePainter.drawRect(pixmapRect.adjusted(1, 1, -2, -2));
                    groovePainter.end();
                    QPixmapCache::insert(groovePixmapName, cache);
                }
                painter->drawPixmap(groove.topLeft(), cache);

                // draw blue groove highlight
                QRect clipRect;
                groovePixmapName += QLatin1String("_blue");
                if (!QPixmapCache::find(groovePixmapName, cache)) {
                    cache = QPixmap(pixmapRect.size());
                    cache.fill(Qt::transparent);
                    QPainter groovePainter(&cache);
                    QLinearGradient gradient;
                    if (horizontal) {
                        gradient.setStart(pixmapRect.center().x(), pixmapRect.top());
                        gradient.setFinalStop(pixmapRect.center().x(), pixmapRect.bottom());
                    }
                    else {
                        gradient.setStart(pixmapRect.left(), pixmapRect.center().y());
                        gradient.setFinalStop(pixmapRect.right(), pixmapRect.center().y());
                    }
                    groovePainter.setPen(QPen(activeHighlight.darker(150), 0));
                    gradient.setColorAt(0, activeHighlight.darker(120));
                    gradient.setColorAt(1, activeHighlight.lighter(160));
                    groovePainter.setBrush(gradient);
                    groovePainter.drawRect(pixmapRect.adjusted(1, 1, -2, -2));
                    groovePainter.end();
                    QPixmapCache::insert(groovePixmapName, cache);
                }
                if (horizontal) {
                    if (slider->upsideDown)
                        clipRect = QRect(handle.right(), groove.top(), groove.right() - handle.right(), groove.height());
                    else
                        clipRect = QRect(groove.left(), groove.top(), handle.left(), groove.height());
                } else {
                    if (slider->upsideDown)
                        clipRect = QRect(groove.left(), handle.bottom(), groove.width(), groove.height() - handle.bottom());
                    else
                        clipRect = QRect(groove.left(), groove.top(), groove.width(), handle.top() - groove.top());
                }
                painter->save();
                painter->setClipRect(clipRect.adjusted(0, 0, 1, 1));
                painter->drawPixmap(groove.topLeft(), cache);
                painter->restore();
            }

            // draw handle
            if ((option->subControls & SC_SliderHandle) ) {
                QString handlePixmapName = QStyleHelper::uniqueName(QLatin1String("slider_handle"), option, handle.size());
                if (!QPixmapCache::find(handlePixmapName, cache)) {
                    cache = QPixmap(handle.size());
                    cache.fill(Qt::transparent);
                    QRect pixmapRect(0, 0, handle.width(), handle.height());
                    QPainter handlePainter(&cache);

                    QColor gradientStartColor = mergedColors(option->palette.button().color().lighter(155),
                                                             dark.lighter(155), 50);
                    QColor gradientStopColor = gradientStartColor.darker(108);
                    QRect gradRect = pixmapRect.adjusted(2, 2, -2, -2);

                    QColor gradientBgStartColor = gradientStartColor;
                    QColor gradientBgStopColor = gradientStopColor;

                    QColor outline = option->state & State_Enabled ? dark : dark.lighter(130);
                    if (option->state & State_Enabled && option->activeSubControls & SC_SliderHandle) {
                        gradientBgStartColor = option->palette.highlight().color().lighter(180);
                        gradientBgStopColor = option->palette.highlight().color().lighter(110);
                        outline = option->palette.highlight().color().darker(130);
                    }

                    // gradient fill
                    QRect r = pixmapRect.adjusted(1, 1, -1, -1);

                    qt_cleanlooks_draw_gradient(&handlePainter, gradRect,
                                                gradientBgStartColor,
                                                gradientBgStopColor,
                                                horizontal ? TopDown : FromLeft, option->palette.button());

                    handlePainter.setPen(QPen(outline.darker(110), 1));
                    handlePainter.drawLine(QPoint(r.left(), r.top() + 3), QPoint(r.left(), r.bottom() - 3));
                    handlePainter.drawLine(QPoint(r.right(), r.top() + 3), QPoint(r.right(), r.bottom() - 3));
                    handlePainter.drawLine(QPoint(r.left() + 3, r.bottom()), QPoint(r.right() - 3, r.bottom()));

                    handlePainter.save();
                    handlePainter.setRenderHint(QPainter::Antialiasing);
                    handlePainter.translate(0.5, 0.5);
                    const QLine lines[4] = {
                        QLine(QPoint(r.left(), r.bottom() - 2), QPoint(r.left() + 2, r.bottom())),
                        QLine(QPoint(r.left(), r.top() + 2), QPoint(r.left() + 2, r.top())),
                        QLine(QPoint(r.right(), r.bottom() - 2), QPoint(r.right() - 2, r.bottom())),
                        QLine(QPoint(r.right(), r.top() + 2), QPoint(r.right() - 2, r.top()))
                    };
                    handlePainter.drawLines(lines, 4);
                    handlePainter.restore();;
                    handlePainter.setPen(QPen(outline.darker(130), 1));
                    handlePainter.drawLine(QPoint(r.left() + 3, r.top()), QPoint(r.right() - 3, r.top()));
                    QColor cornerAlpha = outline.darker(120);
                    cornerAlpha.setAlpha(80);

                    handlePainter.setPen(cornerAlpha);
                    if (horizontal) {
                        handlePainter.drawLine(QPoint(r.left() + 6, r.top()), QPoint(r.left() + 6, r.bottom()));
                        handlePainter.drawLine(QPoint(r.right() - 6, r.top()), QPoint(r.right() - 6, r.bottom()));
                    } else {
                        handlePainter.drawLine(QPoint(r.left(), r.top() + 6), QPoint(r.right(), r.top() + 6));
                        handlePainter.drawLine(QPoint(r.left(), r.bottom() - 6), QPoint(r.right(), r.bottom() - 6));
                    }

                    //handle shadow
                    handlePainter.setPen(shadowAlpha);
                    handlePainter.drawLine(QPoint(r.left() + 2, r.bottom() + 1), QPoint(r.right() - 2, r.bottom() + 1));
                    handlePainter.drawLine(QPoint(r.right() + 1, r.bottom() - 3), QPoint(r.right() + 1, r.top() + 4));
                    handlePainter.drawLine(QPoint(r.right() - 1, r.bottom()), QPoint(r.right() + 1, r.bottom() - 2));

                    qt_cleanlooks_draw_gradient(&handlePainter, horizontal ?
                        gradRect.adjusted(6, 0, -6, 0) : gradRect.adjusted(0, 6, 0, -6),
                        gradientStartColor,
                        gradientStopColor.darker(106),
                        horizontal ? TopDown : FromLeft,
                        option->palette.button());

                    //draw grips
                    for (int i = -3; i< 6 ; i += 3) {
                        for (int j = -3; j< 6 ; j += 3) {
                            handlePainter.fillRect(r.center().x() + i, r.center().y() + j, 2, 2, highlightAlpha);
                            handlePainter.setPen(gripShadow);
                            handlePainter.drawPoint(r.center().x() + i, r.center().y() + j );
                        }
                    }
                    handlePainter.end();
                    QPixmapCache::insert(handlePixmapName, cache);
                }

                painter->drawPixmap(handle.topLeft(), cache);

                if (slider->state & State_HasFocus) {
                    QStyleOptionFocusRect fropt;
                    fropt.QStyleOption::operator=(*slider);
                    fropt.rect = slider->rect;
                    proxy()->drawPrimitive(PE_FrameFocusRect, &fropt, painter, widget);
                }
            }
            if (option->subControls & SC_SliderTickmarks) {
                painter->setPen(darkOutline);
                int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
                int available = proxy()->pixelMetric(PM_SliderSpaceAvailable, slider, widget);
                int interval = slider->tickInterval;
                if (interval <= 0) {
                    interval = slider->singleStep;
                    if (QStyle::sliderPositionFromValue(slider->minimum, slider->maximum, interval,
                                                        available)
                        - QStyle::sliderPositionFromValue(slider->minimum, slider->maximum,
                                                        0, available) < 3)
                        interval = slider->pageStep;
                }
                if (interval <= 0)
                    interval = 1;

                int v = slider->minimum;
                int len = proxy()->pixelMetric(PM_SliderLength, slider, widget);
                while (v <= slider->maximum + 1) {
                    if (v == slider->maximum + 1 && interval == 1)
                        break;
                    const int v_ = qMin(v, slider->maximum);
                    int pos = sliderPositionFromValue(slider->minimum, slider->maximum,
                                                    v_, (horizontal
                                                        ? slider->rect.width()
                                                        : slider->rect.height()) - len,
                                                    slider->upsideDown) + len / 2;
                    int extra = 2 - ((v_ == slider->minimum || v_ == slider->maximum) ? 1 : 0);

                    if (horizontal) {
                        if (ticksAbove) {
                            painter->drawLine(pos, slider->rect.top() + extra,
                                pos, slider->rect.top() + tickSize);
                        }
                        if (ticksBelow) {
                            painter->drawLine(pos, slider->rect.bottom() - extra,
                                            pos, slider->rect.bottom() - tickSize);
                        }
                    } else {
                        if (ticksAbove) {
                            painter->drawLine(slider->rect.left() + extra, pos,
                                            slider->rect.left() + tickSize, pos);
                        }
                        if (ticksBelow) {
                            painter->drawLine(slider->rect.right() - extra, pos,
                                            slider->rect.right() - tickSize, pos);
                        }
                    }
                    // in the case where maximum is max int
                    int nextInterval = v + interval;
                    if (nextInterval < v)
                        break;
                    v = nextInterval;
                }
            }
            painter->setBrush(oldBrush);
            painter->setPen(oldPen);
        }
        break;
#endif // QT_NO_SLIDER
#ifndef QT_NO_DIAL
    case CC_Dial:
        if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(option))
            QStyleHelper::drawDial(dial, painter);
        break;
#endif // QT_NO_DIAL
        default:
            QWindowsStyle::drawComplexControl(control, option, painter, widget);
        break;
    }
}

/*!
  \reimp
*/
int QCleanlooksStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
{
    int ret = -1;
    switch (metric) {
    case PM_ToolTipLabelFrameWidth:
        ret = 2;
        break;
    case PM_ButtonDefaultIndicator:
        ret = 0;
        break;
    case PM_ButtonShiftHorizontal:
    case PM_ButtonShiftVertical:
        ret = 0;
        break;
    case PM_MessageBoxIconSize:
        ret = 48;
        break;
    case PM_ListViewIconSize:
        ret = 24;
        break;
    case PM_DialogButtonsSeparator:
    case PM_SplitterWidth:
        ret = 6;
        break;
    case PM_ScrollBarSliderMin:
        ret = 26;
        break;
    case PM_MenuPanelWidth: //menu framewidth
        ret = 2;
        break;
    case PM_TitleBarHeight:
        ret = 24;
        break;
    case PM_ScrollBarExtent:
        ret = 15;
        break;
    case PM_SliderThickness:
        ret = 15;
        break;
    case PM_SliderLength:
        ret = 27;
        break;
    case PM_DockWidgetTitleMargin:
        ret = 1;
        break;
    case PM_MenuBarVMargin:
        ret = 1;
        break;
    case PM_DefaultFrameWidth:
        ret = 2;
        break;
    case PM_SpinBoxFrameWidth:
        ret = 3;
        break;
    case PM_MenuBarItemSpacing:
        ret = 6;
        break;
    case PM_MenuBarHMargin:
        ret = 0;
        break;
    case PM_ToolBarHandleExtent:
        ret = 9;
        break;
    case PM_ToolBarItemSpacing:
        ret = 2;
        break;
    case PM_ToolBarFrameWidth:
        ret = 0;
        break;
    case PM_ToolBarItemMargin:
        ret = 1;
        break;
    case PM_SmallIconSize:
        ret = 16;
        break;
    case PM_ButtonIconSize:
        ret = 24;
        break;
    case PM_MenuVMargin:
    case PM_MenuHMargin:
        ret = 0;
        break;
    case PM_DockWidgetTitleBarButtonMargin:
        ret = 4;
        break;
    case PM_MaximumDragDistance:
        return -1;
    case PM_TabCloseIndicatorWidth:
    case PM_TabCloseIndicatorHeight:
        return 20;
    default:
        break;
    }

    return ret != -1 ? ret : QWindowsStyle::pixelMetric(metric, option, widget);
}

/*!
  \reimp
*/
QSize QCleanlooksStyle::sizeFromContents(ContentsType type, const QStyleOption *option,
                                        const QSize &size, const QWidget *widget) const
{
    QSize newSize = QWindowsStyle::sizeFromContents(type, option, size, widget);
    switch (type) {
    case CT_PushButton:
        if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
            if (!btn->text.isEmpty() && newSize.width() < 80)
                newSize.setWidth(80);
            if (!btn->icon.isNull() && btn->iconSize.height() > 16)
                newSize -= QSize(0, 2);
            newSize += QSize(0, 1);
        }
        if (const QPushButton *button = qobject_cast<const QPushButton *>(widget)) {
            if (qobject_cast<const QDialogButtonBox *>(button->parentWidget())) {
                if (newSize.height() < 32)
                    newSize.setHeight(32);
            }
        }
        break;
#ifndef QT_NO_GROUPBOX
    case CT_GroupBox:
        // Since we use a bold font we have to recalculate base width
        if (const QGroupBox *gb = qobject_cast<const QGroupBox*>(widget)) {
            QFont font = gb->font();
            font.setBold(true);
            QFontMetrics metrics(font);
            int baseWidth = metrics.width(gb->title()) + metrics.width(QLatin1Char(' '));
            if (gb->isCheckable()) {
                baseWidth += proxy()->pixelMetric(QStyle::PM_IndicatorWidth, option, widget);
                baseWidth += proxy()->pixelMetric(QStyle::PM_CheckBoxLabelSpacing, option, widget);
            }
            newSize.setWidth(qMax(baseWidth, newSize.width()));
        }
        newSize += QSize(0, 1);
        break;
#endif //QT_NO_GROUPBOX
    case CT_RadioButton:
    case CT_CheckBox:
        newSize += QSize(0, 1);
        break;
    case CT_ToolButton:
#ifndef QT_NO_TOOLBAR
        if (widget && qobject_cast<QToolBar *>(widget->parentWidget()))
            newSize += QSize(4, 6);
#endif // QT_NO_TOOLBAR
        break;
    case CT_SpinBox:
        newSize += QSize(0, -2);
        break;
    case CT_ComboBox:
        newSize += QSize(2, 4);
        break;
    case CT_LineEdit:
        newSize += QSize(0, 4);
        break;
    case CT_MenuBarItem:
	    newSize += QSize(0, 2);
	    break;
    case CT_MenuItem:
        if (const QStyleOptionMenuItem *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
            if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
                if (!menuItem->text.isEmpty()) {
                    newSize.setHeight(menuItem->fontMetrics.height());
                }
            }
#ifndef QT_NO_COMBOBOX
            else if (!menuItem->icon.isNull()) {
                if (const QComboBox *combo = qobject_cast<const QComboBox*>(widget)) {
                    newSize.setHeight(qMax(combo->iconSize().height() + 2, newSize.height()));
                }
            }
#endif // QT_NO_COMBOBOX
        }
        break;
    case CT_SizeGrip:
	    newSize += QSize(4, 4);
	break;
    case CT_MdiControls:
        if (const QStyleOptionComplex *styleOpt = qstyleoption_cast<const QStyleOptionComplex *>(option)) {
            int width = 0;
            if (styleOpt->subControls & SC_MdiMinButton)
                width += 19 + 1;
            if (styleOpt->subControls & SC_MdiNormalButton)
                width += 19 + 1;
            if (styleOpt->subControls & SC_MdiCloseButton)
                width += 19 + 1;
            newSize = QSize(width, 19);
        } else {
            newSize = QSize(60, 19);
        }
        break;
    default:
        break;
    }
    return newSize;
}

/*!
  \reimp
*/
void QCleanlooksStyle::polish(QApplication *app)
{
    QWindowsStyle::polish(app);
}

/*!
  \reimp
*/
void QCleanlooksStyle::polish(QWidget *widget)
{
    QWindowsStyle::polish(widget);
    if (qobject_cast<QAbstractButton*>(widget)
#ifndef QT_NO_COMBOBOX
        || qobject_cast<QComboBox *>(widget)
#endif
#ifndef QT_NO_PROGRESSBAR
        || qobject_cast<QProgressBar *>(widget)
#endif
#ifndef QT_NO_SCROLLBAR
        || qobject_cast<QScrollBar *>(widget)
#endif
#ifndef QT_NO_SPLITTER
        || qobject_cast<QSplitterHandle *>(widget)
#endif
        || qobject_cast<QAbstractSlider *>(widget)
#ifndef QT_NO_SPINBOX
        || qobject_cast<QAbstractSpinBox *>(widget)
#endif
        || (widget->inherits("QWorkspaceChild"))
        || (widget->inherits("QDockSeparator"))
        || (widget->inherits("QDockWidgetSeparator"))
        ) {
        widget->setAttribute(Qt::WA_Hover, true);
    }
}

/*!
  \reimp
*/
void QCleanlooksStyle::polish(QPalette &pal)
{
    QWindowsStyle::polish(pal);
    //this is a workaround for some themes such as Human, where the contrast
    //between text and background is too low.
    QColor highlight = pal.highlight().color();
    QColor highlightText = pal.highlightedText().color();
    if (qAbs(qGray(highlight.rgb()) - qGray(highlightText.rgb())) < 150) {
        if (qGray(highlightText.rgb()) < 128)
            pal.setBrush(QPalette::Highlight, highlight.lighter(145));
    }
}

/*!
  \reimp
*/
void QCleanlooksStyle::unpolish(QWidget *widget)
{
    QWindowsStyle::unpolish(widget);
    if (qobject_cast<QAbstractButton*>(widget)
#ifndef QT_NO_COMBOBOX
        || qobject_cast<QComboBox *>(widget)
#endif
#ifndef QT_NO_PROGRESSBAR
        || qobject_cast<QProgressBar *>(widget)
#endif
#ifndef QT_NO_SCROLLBAR
        || qobject_cast<QScrollBar *>(widget)
#endif
#ifndef QT_NO_SPLITTER
        || qobject_cast<QSplitterHandle *>(widget)
#endif
        || qobject_cast<QAbstractSlider *>(widget)
#ifndef QT_NO_SPINBOX
        || qobject_cast<QAbstractSpinBox *>(widget)
#endif
        || (widget->inherits("QWorkspaceChild"))
        || (widget->inherits("QDockSeparator"))
        || (widget->inherits("QDockWidgetSeparator"))
        ) {
        widget->setAttribute(Qt::WA_Hover, false);
    }
}

/*!
  \reimp
*/
void QCleanlooksStyle::unpolish(QApplication *app)
{
    QWindowsStyle::unpolish(app);
}

/*!
  \reimp
*/
QRect QCleanlooksStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option,
                                       SubControl subControl, const QWidget *widget) const
{
    QRect rect = QWindowsStyle::subControlRect(control, option, subControl, widget);

    switch (control) {
#ifndef QT_NO_SLIDER
    case CC_Slider:
        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
            int tickSize = proxy()->pixelMetric(PM_SliderTickmarkOffset, option, widget);
            switch (subControl) {
            case SC_SliderHandle: {
                if (slider->orientation == Qt::Horizontal) {
                    rect.setHeight(proxy()->pixelMetric(PM_SliderThickness));
                    rect.setWidth(proxy()->pixelMetric(PM_SliderLength));
                    int centerY = slider->rect.center().y() - rect.height() / 2;
                    if (slider->tickPosition & QSlider::TicksAbove)
                        centerY += tickSize;
                    if (slider->tickPosition & QSlider::TicksBelow)
                        centerY -= tickSize;
                    rect.moveTop(centerY);
                } else {
                    rect.setWidth(proxy()->pixelMetric(PM_SliderThickness));
                    rect.setHeight(proxy()->pixelMetric(PM_SliderLength));
                    int centerX = slider->rect.center().x() - rect.width() / 2;
                    if (slider->tickPosition & QSlider::TicksAbove)
                        centerX += tickSize;
                    if (slider->tickPosition & QSlider::TicksBelow)
                        centerX -= tickSize;
                    rect.moveLeft(centerX);
                }
            }
                break;
            case SC_SliderGroove: {
                QPoint grooveCenter = slider->rect.center();
                if (slider->orientation == Qt::Horizontal) {
                    rect.setHeight(7);
                    if (slider->tickPosition & QSlider::TicksAbove)
                        grooveCenter.ry() += tickSize;
                    if (slider->tickPosition & QSlider::TicksBelow)
                        grooveCenter.ry() -= tickSize;
                } else {
                    rect.setWidth(7);
                    if (slider->tickPosition & QSlider::TicksAbove)
                        grooveCenter.rx() += tickSize;
                    if (slider->tickPosition & QSlider::TicksBelow)
                        grooveCenter.rx() -= tickSize;
                }
                rect.moveCenter(grooveCenter);
                break;
            }
            default:
                break;
            }
        }
        break;
#endif // QT_NO_SLIDER
    case CC_ScrollBar:
        break;
#ifndef QT_NO_SPINBOX
    case CC_SpinBox:
        if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(option)) {
            QSize bs;
            int center = spinbox->rect.height() / 2;
            int fw = spinbox->frame ? proxy()->pixelMetric(PM_SpinBoxFrameWidth, spinbox, widget) : 0;
            int y = fw;
            bs.setHeight(qMax(8, spinbox->rect.height()/2 - y));
            bs.setWidth(15);
            int x, lx, rx;
            x = spinbox->rect.width() - y - bs.width() + 2;
            lx = fw;
            rx = x - fw;
            switch (subControl) {
            case SC_SpinBoxUp:
                if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
                    return QRect();
                rect = QRect(x, fw, bs.width(), center - fw);
                break;
            case SC_SpinBoxDown:
                if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons)
                    return QRect();

                rect = QRect(x, center, bs.width(), spinbox->rect.bottom() - center - fw + 1);
                break;
            case SC_SpinBoxEditField:
                if (spinbox->buttonSymbols == QAbstractSpinBox::NoButtons) {
                    rect = QRect(lx, fw, spinbox->rect.width() - 2*fw, spinbox->rect.height() - 2*fw);
                } else {
                    rect = QRect(lx, fw, rx - qMax(fw - 1, 0), spinbox->rect.height() - 2*fw);
                }
                break;
            case SC_SpinBoxFrame:
                rect = spinbox->rect;
            default:
                break;
            }
            rect = visualRect(spinbox->direction, spinbox->rect, rect);
        }
        break;
#endif // Qt_NO_SPINBOX
#ifndef QT_NO_GROUPBOX
    case CC_GroupBox:
        if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
            int topMargin = 0;
            int topHeight = 0;
            int verticalAlignment = proxy()->styleHint(SH_GroupBox_TextLabelVerticalAlignment, groupBox, widget);
            bool flat = groupBox->features & QStyleOptionFrameV2::Flat;
            if (!groupBox->text.isEmpty()) {
                topHeight = groupBox->fontMetrics.height();
                if (verticalAlignment & Qt::AlignVCenter)
                    topMargin = topHeight / 2;
                else if (verticalAlignment & Qt::AlignTop)
                    topMargin = topHeight;
            }
            QRect frameRect = groupBox->rect;
            frameRect.setTop(topMargin);
            if (subControl == SC_GroupBoxFrame) {
                return rect;
            }
            else if (subControl == SC_GroupBoxContents) {
                if( flat ) {
                    int margin = 0;
                    int leftMarginExtension = 16;
                    rect = frameRect.adjusted(leftMarginExtension + margin, margin + topHeight, -margin, -margin);
                }
                break;
            }
            if(flat) {
                if (const QGroupBox *groupBoxWidget = qobject_cast<const QGroupBox *>(widget)) {
                    //Prepare metrics for a bold font
                    QFont font = widget->font();
                    font.setBold(true);
                    QFontMetrics fontMetrics(font);

                    QSize textRect = fontMetrics.boundingRect(groupBoxWidget->title()).size() + QSize(2, 2);
                    if (subControl == SC_GroupBoxCheckBox) {
                        int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, option, widget);
                        int indicatorHeight = proxy()->pixelMetric(PM_IndicatorHeight, option, widget);
                        rect.setWidth(indicatorWidth);
                        rect.setHeight(indicatorHeight);
                        rect.moveTop((fontMetrics.height() - indicatorHeight) / 2 + 2);
                    } else if (subControl == SC_GroupBoxLabel) {
                        rect.setSize(textRect);
                    }
                }
            }
        }
        return rect;
#ifndef QT_NO_COMBOBOX
    case CC_ComboBox:
        switch (subControl) {
        case SC_ComboBoxArrow:
            rect = visualRect(option->direction, option->rect, rect);
            rect.setRect(rect.right() - 18, rect.top() - 2,
                         19, rect.height() + 4);
            rect = visualRect(option->direction, option->rect, rect);
            break;
        case SC_ComboBoxEditField: {
            int frameWidth = proxy()->pixelMetric(PM_DefaultFrameWidth);
            rect = visualRect(option->direction, option->rect, rect);
            rect.setRect(option->rect.left() + frameWidth, option->rect.top() + frameWidth,
                         option->rect.width() - 19 - 2 * frameWidth,
                         option->rect.height() - 2 * frameWidth);
            if (const QStyleOptionComboBox *box = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
                if (!box->editable) {
                    rect.adjust(2, 0, 0, 0);
                    if (box->state & (State_Sunken | State_On))
                        rect.translate(1, 1);
                }
            }
            rect = visualRect(option->direction, option->rect, rect);
            break;
        }
        default:
            break;
        }
        break;
#endif // QT_NO_COMBOBOX
#endif //QT_NO_GROUPBOX
        case CC_TitleBar:
        if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(option)) {
            SubControl sc = subControl;
            QRect &ret = rect;
            const int indent = 3;
            const int controlTopMargin = 3;
            const int controlBottomMargin = 3;
            const int controlWidthMargin = 2;
            const int controlHeight = tb->rect.height() - controlTopMargin - controlBottomMargin ;
            const int delta = controlHeight + controlWidthMargin;
            int offset = 0;

            bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
            bool isMaximized = tb->titleBarState & Qt::WindowMaximized;

            switch (sc) {
            case SC_TitleBarLabel:
                if (tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)) {
                    ret = tb->rect;
                    if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
                        ret.adjust(delta, 0, -delta, 0);
                    if (tb->titleBarFlags & Qt::WindowMinimizeButtonHint)
                        ret.adjust(0, 0, -delta, 0);
                    if (tb->titleBarFlags & Qt::WindowMaximizeButtonHint)
                        ret.adjust(0, 0, -delta, 0);
                    if (tb->titleBarFlags & Qt::WindowShadeButtonHint)
                        ret.adjust(0, 0, -delta, 0);
                    if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
                        ret.adjust(0, 0, -delta, 0);
                }
                break;
            case SC_TitleBarContextHelpButton:
                if (tb->titleBarFlags & Qt::WindowContextHelpButtonHint)
                    offset += delta;
            case SC_TitleBarMinButton:
                if (!isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
                    offset += delta;
                else if (sc == SC_TitleBarMinButton)
                    break;
            case SC_TitleBarNormalButton:
                if (isMinimized && (tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
                    offset += delta;
                else if (isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
                    offset += delta;
                else if (sc == SC_TitleBarNormalButton)
                    break;
            case SC_TitleBarMaxButton:
                if (!isMaximized && (tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
                    offset += delta;
                else if (sc == SC_TitleBarMaxButton)
                    break;
            case SC_TitleBarShadeButton:
                if (!isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
                    offset += delta;
                else if (sc == SC_TitleBarShadeButton)
                    break;
            case SC_TitleBarUnshadeButton:
                if (isMinimized && (tb->titleBarFlags & Qt::WindowShadeButtonHint))
                    offset += delta;
                else if (sc == SC_TitleBarUnshadeButton)
                    break;
            case SC_TitleBarCloseButton:
                if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
                    offset += delta;
                else if (sc == SC_TitleBarCloseButton)
                    break;
                ret.setRect(tb->rect.right() - indent - offset, tb->rect.top() + controlTopMargin,
                            controlHeight, controlHeight);
                break;
            case SC_TitleBarSysMenu:
                if (tb->titleBarFlags & Qt::WindowSystemMenuHint) {
                    ret.setRect(tb->rect.left() + controlWidthMargin + indent, tb->rect.top() + controlTopMargin,
                                controlHeight, controlHeight);
                }
                break;
            default:
                break;
            }
            ret = visualRect(tb->direction, tb->rect, ret);
        }
        break;
    default:
        break;
    }

    return rect;
}


/*!
  \reimp
*/
QRect QCleanlooksStyle::itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const
{
    return QWindowsStyle::itemPixmapRect(r, flags, pixmap);
}

/*!
  \reimp
*/
void QCleanlooksStyle::drawItemPixmap(QPainter *painter, const QRect &rect,
                            int alignment, const QPixmap &pixmap) const
{
    QWindowsStyle::drawItemPixmap(painter, rect, alignment, pixmap);
}

/*!
  \reimp
*/
QStyle::SubControl QCleanlooksStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
                              const QPoint &pt, const QWidget *w) const
{
    return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
}

/*!
  \reimp
*/
QPixmap QCleanlooksStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
                                        const QStyleOption *opt) const
{
    return QWindowsStyle::generatedIconPixmap(iconMode, pixmap, opt);
}

/*!
  \reimp
*/
int QCleanlooksStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget,
                               QStyleHintReturn *returnData) const
{
    int ret = 0;
    switch (hint) {
    case SH_ScrollBar_MiddleClickAbsolutePosition:
        ret = true;
        break;
    case SH_EtchDisabledText:
        ret = 1;
        break;
    case SH_Menu_AllowActiveAndDisabled:
        ret = false;
        break;
    case SH_MainWindow_SpaceBelowMenuBar:
        ret = 0;
        break;
    case SH_MenuBar_MouseTracking:
        ret = 1;
        break;
    case SH_TitleBar_AutoRaise:
        ret = 1;
        break;
    case SH_TitleBar_NoBorder:
        ret = 1;
        break;
    case SH_ItemView_ShowDecorationSelected:
        ret = true;
        break;
    case SH_Table_GridLineColor:
        if (option) {
            ret = option->palette.background().color().darker(120).rgb();
            break;
        }
    case SH_ComboBox_Popup:
#ifdef QT3_SUPPORT
        if (widget && widget->inherits("Q3ComboBox"))
            return 0;
#endif
        if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(option))
            ret = !cmb->editable;
        else
            ret = 0;
        break;
    case SH_WindowFrame_Mask:
        ret = 1;
        if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask *>(returnData)) {
            //left rounded corner
            mask->region = option->rect;
            mask->region -= QRect(option->rect.left(), option->rect.top(), 5, 1);
            mask->region -= QRect(option->rect.left(), option->rect.top() + 1, 3, 1);
            mask->region -= QRect(option->rect.left(), option->rect.top() + 2, 2, 1);
            mask->region -= QRect(option->rect.left(), option->rect.top() + 3, 1, 2);

            //right rounded corner
            mask->region -= QRect(option->rect.right() - 4, option->rect.top(), 5, 1);
            mask->region -= QRect(option->rect.right() - 2, option->rect.top() + 1, 3, 1);
            mask->region -= QRect(option->rect.right() - 1, option->rect.top() + 2, 2, 1);
            mask->region -= QRect(option->rect.right() , option->rect.top() + 3, 1, 2);
        }
        break;
    case SH_MessageBox_TextInteractionFlags:
        ret = Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse;
        break;
    case SH_DialogButtonBox_ButtonsHaveIcons:
        ret = true;
        break;
    case SH_MessageBox_CenterButtons:
        ret = false;
        break;
#ifndef QT_NO_WIZARD
    case SH_WizardStyle:
        ret = QWizard::ClassicStyle;
        break;
#endif
    case SH_ItemView_ArrowKeysNavigateIntoChildren:
        ret = false;
        break;
    case SH_Menu_SubMenuPopupDelay:
        ret = 225; // default from GtkMenu
        break;
    default:
        ret = QWindowsStyle::styleHint(hint, option, widget, returnData);
        break;
    }
    return ret;
}

/*! \reimp */
QRect QCleanlooksStyle::subElementRect(SubElement sr, const QStyleOption *opt, const QWidget *w) const
{
    QRect r = QWindowsStyle::subElementRect(sr, opt, w);
    switch (sr) {
    case SE_PushButtonFocusRect:
        r.adjust(0, 1, 0, -1);
        break;
    case SE_DockWidgetTitleBarText: {
        const QStyleOptionDockWidgetV2 *v2
            = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
        bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
        if (verticalTitleBar) {
            r.adjust(0, 0, 0, -4);
        } else {
            if (opt->direction == Qt::LeftToRight)
                r.adjust(4, 0, 0, 0);
            else
                r.adjust(0, 0, -4, 0);
        }

        break;
    }
    case SE_ProgressBarContents:
        r = subElementRect(SE_ProgressBarGroove, opt, w);
        break;
    default:
        break;
    }
    return r;
}

/*!
    \internal
*/
QIcon QCleanlooksStyle::standardIconImplementation(StandardPixmap standardIcon,
                                                  const QStyleOption *option,
                                                  const QWidget *widget) const
{
    return QWindowsStyle::standardIconImplementation(standardIcon, option, widget);
}

/*!
 \reimp
 */
QPixmap QCleanlooksStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
                                      const QWidget *widget) const
{
    QPixmap pixmap;

#ifndef QT_NO_IMAGEFORMAT_XPM
    switch (standardPixmap) {
    case SP_TitleBarNormalButton:
        return QPixmap((const char **)dock_widget_restore_xpm);
    case SP_TitleBarMinButton:
        return QPixmap((const char **)workspace_minimize);
    case SP_TitleBarCloseButton:
    case SP_DockWidgetCloseButton:
        return QPixmap((const char **)dock_widget_close_xpm);

    default:
        break;
    }
#endif //QT_NO_IMAGEFORMAT_XPM

    return QWindowsStyle::standardPixmap(standardPixmap, opt, widget);
}

QT_END_NAMESPACE

#endif // QT_NO_STYLE_CLEANLOOKS || QT_PLUGIN