<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "leveldb/env.h"

#include "windows.h"

namespace leveldb {

static Status IOError(const std::string& context, DWORD errorCode) {
  LPTSTR errorText = NULL;

  FormatMessage(
   FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
   NULL,
   errorCode,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR)&errorText,
   0,
   NULL);

   std::string errorMsg;
   if ( NULL != errorText ) {
     errorMsg = errorText;
     LocalFree(errorText);
     errorText = NULL;
   }

   return Status::IOError(context, errorMsg);
}

class WindowsSequentialFile : public SequentialFile {
  private:
  std::string& mFilename;
  HANDLE hFile;

  public:
  WindowsSequentialFile(const std::string& filename, const HANDLE file)
  : mFilename(filename), hFile(file) { }

  virtual ~WindowsSequentialFile() {
    CloseHandle(hFile);
  }

  virtual Status Read(size_t n, Slice* result, char* scratch) {
    DWORD r;
    if(ReadFile(hFile, scratch, n, &r, NULL)){
      result = Slice(scratch, r);
      return Status::OK();
    } else {
      return IOError(mFilename, GetLastError());
    }
  }
};

class WindowsEnv : public Env {
	public:
  WindowsEnv() {}
  virtual ~WindowsEnv() {}

  virtual Status NewSequentialFile(const std::string& fname,
                                   SequentialFile** result) {
    HANDLE hFile = CreateFile(fname.c_str(),
       GENERIC_READ,
       FILE_SHARE_READ,
       NULL,
       OPEN_EXISTING,
       FILE_ATTRIBUTE_NORMAL,
       NULL);

       if (hFile == INVALID_HANDLE_VALUE) {
         *result = NULL;
         return IOError(fname, GetLastError());
       } else {
         *result = new WindowsSequentialFile(fname, hFile);
         return Status::OK();
       }
  }

  virtual Status NewRandomAccessFile(const std::string& fname,
                                     RandomAccessFile** result) {
    return Status::NotSupported("not implemented");
  }

  virtual Status NewWritableFile(const std::string& fname,
                                 WritableFile** result) {
    return Status::NotSupported("not implemented");
  }

  virtual bool FileExists(const std::string& fname){
    return Status::NotSupported("not implemented");
  }

  virtual Status GetChildren(const std::string& dir,
                             std::vector<std::string>* result){
    return Status::NotSupported("not implemented");

  }

  virtual Status DeleteFile(const std::string& fname) {
    return Status::NotSupported("not implemented");
  }

  virtual Status CreateDir(const std::string& dirname) {
    return Status::NotSupported("not implemented");
  }

  virtual Status DeleteDir(const std::string& dirname){
    return Status::NotSupported("not implemented");
  }

  virtual Status GetFileSize(const std::string& fname, uint64_t* file_size){
    return Status::NotSupported("not implemented");
  }

  virtual Status RenameFile(const std::string& src,
                            const std::string& target){
    return Status::NotSupported("not implemented");
  }

  virtual Status LockFile(const std::string& fname, FileLock** lock){
    return Status::NotSupported("not implemented");
  }

  virtual Status UnlockFile(FileLock* lock){
    return Status::NotSupported("not implemented");
  }

  virtual void Schedule(
      void (*function)(void* arg),
      void* arg){
    return Status::NotSupported("not implemented");
  }

  virtual void StartThread(void (*function)(void* arg), void* arg){
    return Status::NotSupported("not implemented");
  }

  virtual Status GetTestDirectory(std::string* path){
    return Status::NotSupported("not implemented");
  }

  virtual Status NewLogger(const std::string& fname, Logger** result){
    return Status::NotSupported("not implemented");
  }

  virtual uint64_t NowMicros(){
    return Status::NotSupported("not implemented");
  }

  virtual void SleepForMicroseconds(int micros){
    return Status::NotSupported("not implemented");
  }

};

Env* Env::Default() {
  return new WindowsEnv();
}

}  // namespace leveldb
<commit_msg>windows wip<commit_after>#include "windows.h"

#include "leveldb/env.h"

namespace leveldb {

static Status IOError(const std::string& context, DWORD errorCode) {
  LPTSTR errorText = NULL;

  FormatMessage(
   FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
   NULL,
   errorCode,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR)&errorText,
   0,
   NULL);

   std::string errorMsg;
   if ( NULL != errorText ) {
     errorMsg = errorText;
     LocalFree(errorText);
     errorText = NULL;
   }

   return Status::IOError(context, errorMsg);
}

class WindowsSequentialFile : public SequentialFile {
  private:
  const std::string& mFilename;
  HANDLE hFile;

  public:
  WindowsSequentialFile(const std::string& filename, const HANDLE file)
  : mFilename(filename), hFile(file) { }

  virtual ~WindowsSequentialFile() {
    CloseHandle(hFile);
  }

  virtual Status Read(size_t n, Slice* result, char* scratch) {
    DWORD r;
    if(ReadFile(hFile, scratch, n, &r, NULL)){
      *result = Slice(scratch, r);
      return Status::OK();
    } else {
      return IOError(mFilename, GetLastError());
    }
  }

  virtual Status Skip(uint64_t n) {
    LARGE_INTEGER li;
    li.QuadPart = n;

    li.LowPart = SetFilePointer(hFile, li.LowPart, &li.HighPart, FILE_CURRENT);
    if(li.LowPart == INVALID_SET_FILE_POINTER) {
      return IOError(mFilename, GetLastError());
    } else {
      return Status::OK();
    }
  }
};

class WindowsWriteableFile : public WritableFile {
  private:
  const std::string& mFilename;
  HANDLE hFile;

  public:
  WindowsWriteableFile(const std::string& filename, const HANDLE file)
  : mFilename(filename), hFile(file) { }

  ~WindowsWriteableFile() {
    CloseHandle(hFile);
  }

  virtual Status Append(const Slice& data) {

  }
  virtual Status Close() {

  }
  virtual Status Flush() {

  }
  virtual Status Sync() {

  }
};

class WindowsEnv : public Env {
	public:
  WindowsEnv() {}
  virtual ~WindowsEnv() {}

  virtual Status NewSequentialFile(const std::string& fname,
                                   SequentialFile** result) {
    HANDLE hFile = CreateFile(fname.c_str(),
       GENERIC_READ,
       FILE_SHARE_READ,
       NULL,
       OPEN_EXISTING,
       FILE_ATTRIBUTE_NORMAL,
       NULL);

       if (hFile == INVALID_HANDLE_VALUE) {
         *result = NULL;
         return IOError(fname, GetLastError());
       } else {
         *result = new WindowsSequentialFile(fname, hFile);
         return Status::OK();
       }
  }

  virtual Status NewRandomAccessFile(const std::string& fname,
                                     RandomAccessFile** result) {
    return Status::NotSupported("not implemented");
  }

  virtual Status NewWritableFile(const std::string& fname,
                                 WritableFile** result) {

    HANDLE hFile = CreateFile(fname.c_str(),
      GENERIC_WRITE,
      FILE_SHARE_WRITE,
      NULL,
      OPEN_EXISTING,
      FILE_ATTRIBUTE_NORMAL,
      NULL);

      if(hFile == INVALID_HANDLE_VALUE) {
        *result = NULL;
        return IOError(fname, GetLastError());
      } else {
        *result = new WindowsWriteableFile(fname, hFile);
        return Status::OK();
      }

  }

  virtual bool FileExists(const std::string& fname){
    //TODO implement
    return false;
  }

  virtual Status GetChildren(const std::string& dir,
                             std::vector<std::string>* result){
    return Status::NotSupported("not implemented");

  }

  virtual Status DeleteFile(const std::string& fname) {
    return Status::NotSupported("not implemented");
  }

  virtual Status CreateDir(const std::string& dirname) {
    return Status::NotSupported("not implemented");
  }

  virtual Status DeleteDir(const std::string& dirname){
    return Status::NotSupported("not implemented");
  }

  virtual Status GetFileSize(const std::string& fname, uint64_t* file_size){
    return Status::NotSupported("not implemented");
  }

  virtual Status RenameFile(const std::string& src,
                            const std::string& target){
    return Status::NotSupported("not implemented");
  }

  virtual Status LockFile(const std::string& fname, FileLock** lock){
    return Status::NotSupported("not implemented");
  }

  virtual Status UnlockFile(FileLock* lock){
    return Status::NotSupported("not implemented");
  }

  virtual void Schedule(
      void (*function)(void* arg),
      void* arg){

    //TODO implement
  }

  virtual void StartThread(void (*function)(void* arg), void* arg){
    //TODO implement
  }

  virtual Status GetTestDirectory(std::string* path){
    return Status::NotSupported("not implemented");
  }

  virtual Status NewLogger(const std::string& fname, Logger** result){
    return Status::NotSupported("not implemented");
  }

  virtual uint64_t NowMicros(){
    //TODO implement
    return 0;
  }

  virtual void SleepForMicroseconds(int micros){
  }

};

Env* Env::Default() {
  return new WindowsEnv();
}

}  // namespace leveldb
<|endoftext|>


<commit_before>/*
    Copyright (C) 2010  George Kiagiadakis <kiagiadakis.george@gmail.com>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "urihandler.h"
#include "element.h"
#include <gst/gstelementfactory.h>
#include <gst/gsturi.h>
#include <QtCore/QUrl>
#include <QtCore/QStringList>

namespace QGst {

//static
bool UriHandler::protocolIsSupported(UriType type, const char *protocol)
{
    return gst_uri_protocol_is_supported(static_cast<GstURIType>(type), protocol);
}

//static
ElementPtr UriHandler::makeFromUri(UriType type, const QUrl & uri, const char *elementName)
{
    GstElement *e = gst_element_make_from_uri(static_cast<GstURIType>(type), uri.toEncoded(), elementName);
    if (e) {
        gst_object_ref_sink(e);
    }
    return ElementPtr::wrap(e, false);
}

UriType UriHandler::uriType() const
{
    return static_cast<UriType>(gst_uri_handler_get_uri_type(object<GstURIHandler>()));
}

QStringList UriHandler::supportedProtocols() const
{
    QStringList result;
    char **protocols = gst_uri_handler_get_protocols(object<GstURIHandler>());
    if (protocols) {
        for (char **p = protocols; p && *p; ++p) {
            result.append(QString::fromUtf8(*p));
        }
    }
    return result;
}

QUrl UriHandler::uri() const
{
    //QUrl::fromEncoded doesn't work because the returned URI
    //is encoded using percent encoding even for slashes.
    return QUrl::fromPercentEncoding(gst_uri_handler_get_uri(object<GstURIHandler>()));
}

bool UriHandler::setUri(const QUrl & uri)
{
    return gst_uri_handler_set_uri(object<GstURIHandler>(), uri.toEncoded());
}

} //namespace QGst
<commit_msg>src/QGst/urihandler.cpp two uri functions now take a GError parameter.<commit_after>/*
    Copyright (C) 2010  George Kiagiadakis <kiagiadakis.george@gmail.com>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "urihandler.h"
#include "element.h"
#include <gst/gstelementfactory.h>
#include <gst/gsturi.h>
#include <QtCore/QUrl>
#include <QtCore/QStringList>

namespace QGst {

//static
bool UriHandler::protocolIsSupported(UriType type, const char *protocol)
{
    return gst_uri_protocol_is_supported(static_cast<GstURIType>(type), protocol);
}

//static
ElementPtr UriHandler::makeFromUri(UriType type, const QUrl & uri, const char *elementName)
{
    GError *error = NULL;
    GstElement *e = gst_element_make_from_uri(static_cast<GstURIType>(type), uri.toEncoded(), elementName, &error);
    if (error) {
	throw QGlib::Error(error);
    }
    if (e) {
        gst_object_ref_sink(e);
    }
    return ElementPtr::wrap(e, false);
}

UriType UriHandler::uriType() const
{
    return static_cast<UriType>(gst_uri_handler_get_uri_type(object<GstURIHandler>()));
}

QStringList UriHandler::supportedProtocols() const
{
    QStringList result;
    char **protocols = gst_uri_handler_get_protocols(object<GstURIHandler>());
    if (protocols) {
        for (char **p = protocols; p && *p; ++p) {
            result.append(QString::fromUtf8(*p));
        }
    }
    return result;
}

QUrl UriHandler::uri() const
{
    //QUrl::fromEncoded doesn't work because the returned URI
    //is encoded using percent encoding even for slashes.
    return QUrl::fromPercentEncoding(gst_uri_handler_get_uri(object<GstURIHandler>()));
}

bool UriHandler::setUri(const QUrl & uri)
{
    GError *error = NULL;
    bool result;
    result = gst_uri_handler_set_uri(object<GstURIHandler>(), uri.toEncoded(), &error);
    if (error) {
	throw QGlib::Error(error);
    }
    return result;
}

} //namespace QGst
<|endoftext|>


<commit_before><commit_msg>coverity#1242892 Untrusted value as argument<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdxmlimp_impl.hxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-17 19:31:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDXMLIMP_IMPL_HXX
#define _SDXMLIMP_IMPL_HXX

#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif

#ifndef _XMLOFF_XMLTKMAP_HXX
#include "xmltkmap.hxx"
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

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

enum SdXMLDocElemTokenMap
{
    XML_TOK_DOC_STYLES,
    XML_TOK_DOC_AUTOSTYLES,
    XML_TOK_DOC_MASTERSTYLES,
    XML_TOK_DOC_META,
    XML_TOK_DOC_BODY,
    XML_TOK_DOC_SCRIPT,
    XML_TOK_DOC_SETTINGS,
    XML_TOK_OFFICE_END = XML_TOK_UNKNOWN
};

enum SdXMLBodyElemTokenMap
{
    XML_TOK_BODY_PAGE,
    XML_TOK_BODY_SETTINGS
};

enum SdXMLStylesElemTokenMap
{
    XML_TOK_STYLES_MASTER_PAGE,
    XML_TOK_STYLES_STYLE,
    XML_TOK_STYLES_PAGE_MASTER,
    XML_TOK_STYLES_PRESENTATION_PAGE_LAYOUT
};

enum SdXMLAutoStylesElemTokenMap
{
    XML_TOK_AUTOSTYLES_STYLE
};

enum SdXMLMasterPageElemTokenMap
{
    XML_TOK_MASTERPAGE_STYLE,
    XML_TOK_MASTERPAGE_NOTES
};

enum SdXMLMasterPageAttrTokenMap
{
    XML_TOK_MASTERPAGE_NAME,
    XML_TOK_MASTERPAGE_DISPLAY_NAME,
    XML_TOK_MASTERPAGE_PAGE_MASTER_NAME,
    XML_TOK_MASTERPAGE_STYLE_NAME,
    XML_TOK_MASTERPAGE_PAGE_LAYOUT_NAME
};

enum SdXMLPageMasterAttrTokenMap
{
    XML_TOK_PAGEMASTER_NAME
};

enum SdXMLPageMasterStyleAttrTokenMap
{
    XML_TOK_PAGEMASTERSTYLE_MARGIN_TOP,
    XML_TOK_PAGEMASTERSTYLE_MARGIN_BOTTOM,
    XML_TOK_PAGEMASTERSTYLE_MARGIN_LEFT,
    XML_TOK_PAGEMASTERSTYLE_MARGIN_RIGHT,
    XML_TOK_PAGEMASTERSTYLE_PAGE_WIDTH,
    XML_TOK_PAGEMASTERSTYLE_PAGE_HEIGHT,
    XML_TOK_PAGEMASTERSTYLE_PAGE_ORIENTATION
};

enum SdXMLDocStyleAttrTokenMap
{
    XML_TOK_DOCSTYLE_NAME,
    XML_TOK_DOCSTYLE_FAMILY,
    XML_TOK_DOCSTYLE_PARENT_STYLE_NAME,
    XML_TOK_DOCSTYLE_AUTOMATIC
};

enum SdXMLDocStyleElemTokenMap
{
    XML_TOK_DOCSTYLE_PROPERTIES,
    XML_TOK_DOCSTYLE_PRESENTATION_PLACEHOLDER
};

enum SdXMLDrawPageAttrTokenMap
{
    XML_TOK_DRAWPAGE_NAME,
    XML_TOK_DRAWPAGE_STYLE_NAME,
    XML_TOK_DRAWPAGE_MASTER_PAGE_NAME,
    XML_TOK_DRAWPAGE_PAGE_LAYOUT_NAME,
    XML_TOK_DRAWPAGE_ID,
    XML_TOK_DRAWPAGE_HREF
};

enum SdXMLDrawPageElemTokenMap
{
    XML_TOK_DRAWPAGE_NOTES
};

enum SdXMLPresentationPlaceholderAttrTokenMap
{
    XML_TOK_PRESENTATIONPLACEHOLDER_OBJECTNAME,
    XML_TOK_PRESENTATIONPLACEHOLDER_X,
    XML_TOK_PRESENTATIONPLACEHOLDER_Y,
    XML_TOK_PRESENTATIONPLACEHOLDER_WIDTH,
    XML_TOK_PRESENTATIONPLACEHOLDER_HEIGHT
};

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

struct SdXMLltXDrawPageId
{
  bool operator()(sal_Int32 nId1, sal_Int32 nId2 ) const
  {
    return nId1 < nId2;
  }
};

typedef std::map< sal_Int32, com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage >, SdXMLltXDrawPageId > DrawPageIdMap;

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

class SvXMLUnitConverter;
class SvXMLTokenMap;
class XMLSdPropHdlFactory;
class XMLPropertySetMapper;
class XMLPropStyleContext;
class SdXMLStylesContext;
class SdXMLMasterStylesContext;

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

class SdXMLImport: public SvXMLImport
{
    com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > mxDocStyleFamilies;
    com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocMasterPages;
    com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocDrawPages;
    com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > mxPageLayouts;

    // contexts for Style and AutoStyle import
    SdXMLMasterStylesContext*   mpMasterStylesContext;

    // token map lists
    SvXMLTokenMap*              mpDocElemTokenMap;
    SvXMLTokenMap*              mpBodyElemTokenMap;
    SvXMLTokenMap*              mpStylesElemTokenMap;
    SvXMLTokenMap*              mpAutoStylesElemTokenMap;
    SvXMLTokenMap*              mpMasterPageElemTokenMap;
    SvXMLTokenMap*              mpMasterPageAttrTokenMap;
    SvXMLTokenMap*              mpPageMasterAttrTokenMap;
    SvXMLTokenMap*              mpPageMasterStyleAttrTokenMap;
    SvXMLTokenMap*              mpDocStyleAttrTokenMap;
    SvXMLTokenMap*              mpDocStyleElemTokenMap;
    SvXMLTokenMap*              mpDrawPageAttrTokenMap;
    SvXMLTokenMap*              mpDrawPageElemTokenMap;
    SvXMLTokenMap*              mpPresentationPlaceholderAttrTokenMap;

    sal_uInt16                  mnStyleFamilyMask;

    sal_Int32                   mnNewPageCount;
    sal_Int32                   mnNewMasterPageCount;

    sal_Bool                    mbIsDraw;
    sal_Bool                    mbLoadDoc;
    sal_Bool                    mbPreview;

    DrawPageIdMap               maDrawPageIds;

    ::rtl::OUString             msPageLayouts;
    ::rtl::OUString             msPreview;

protected:
    // This method is called after the namespace map has been updated, but
    // before a context for the current element has been pushed.
    virtual SvXMLImportContext *CreateContext(sal_uInt16 nPrefix,
      const rtl::OUString& rLocalName,
      const com::sun::star::uno::Reference<
        com::sun::star::xml::sax::XAttributeList>& xAttrList);

public:
    // #110680#
    SdXMLImport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
        sal_Bool bIsDraw, sal_uInt16 nImportFlags = IMPORT_ALL );
    ~SdXMLImport() throw ();

    // XImporter
    virtual void SAL_CALL setTargetDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    // XInitialization
    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    void SetProgress(sal_Int32 nProg);

    virtual void SetViewSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps);
    virtual void SetConfigurationSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aConfigProps);

    // namespace office
    SvXMLImportContext* CreateMetaContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLImportContext* CreateScriptContext( const ::rtl::OUString& rLocalName );
    SvXMLImportContext* CreateBodyContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLStylesContext* CreateStylesContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLStylesContext* CreateAutoStylesContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLImportContext* CreateMasterStylesContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);

    // Styles and AutoStyles contexts
    const SdXMLMasterStylesContext* GetMasterStylesContext() const { return mpMasterStylesContext; }

    sal_uInt16 GetStyleFamilyMask() const { return mnStyleFamilyMask; }
    sal_Bool IsStylesOnlyMode() const { return !mbLoadDoc; }

    const SvXMLTokenMap& GetDocElemTokenMap();
    const SvXMLTokenMap& GetBodyElemTokenMap();
    const SvXMLTokenMap& GetStylesElemTokenMap();
    const SvXMLTokenMap& GetMasterPageElemTokenMap();
    const SvXMLTokenMap& GetMasterPageAttrTokenMap();
    const SvXMLTokenMap& GetPageMasterAttrTokenMap();
    const SvXMLTokenMap& GetPageMasterStyleAttrTokenMap();
    const SvXMLTokenMap& GetDrawPageAttrTokenMap();
    const SvXMLTokenMap& GetDrawPageElemTokenMap();
    const SvXMLTokenMap& GetPresentationPlaceholderAttrTokenMap();

    // export local parameters concerning page access and similar
    const com::sun::star::uno::Reference<
        com::sun::star::container::XNameAccess >& GetLocalDocStyleFamilies() const { return mxDocStyleFamilies; }
    const com::sun::star::uno::Reference<
        com::sun::star::container::XIndexAccess >& GetLocalMasterPages() const { return mxDocMasterPages; }
    const com::sun::star::uno::Reference<
        com::sun::star::container::XIndexAccess >& GetLocalDrawPages() const { return mxDocDrawPages; }

    sal_Int32 GetNewPageCount() const { return mnNewPageCount; }
    void IncrementNewPageCount() { mnNewPageCount++; }
    sal_Int32 GetNewMasterPageCount() const { return mnNewMasterPageCount; }
    void IncrementNewMasterPageCount() { mnNewMasterPageCount++; }

    com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > getPageLayouts() const { return mxPageLayouts; }

    sal_Bool IsDraw() const { return mbIsDraw; }
    sal_Bool IsImpress() const { return !mbIsDraw; }

    // import pool defaults. Parameter contains pool defaults read
    // from input data. These data needs to be set at the model.
    void ImportPoolDefaults(const XMLPropStyleContext* pPool);

    void setDrawPageId( sal_Int32 nId, com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > );
    com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > getDrawPageForId( sal_Int32 nId );

    // #80365#
    virtual void SetStatisticAttributes(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs);

    sal_Bool IsPreview() const { return mbPreview; }

    // XServiceInfo ( : SvXMLExport )
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
};

#endif  //  _SDXMLIMP_HXX
<commit_msg>INTEGRATION: CWS impress14 (1.22.16); FILE MERGED 2004/10/19 14:38:51 cl 1.22.16.1: #i35425# adapt impress header&footer to latest oasis spec<commit_after>/*************************************************************************
 *
 *  $RCSfile: sdxmlimp_impl.hxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-03 16:40:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDXMLIMP_IMPL_HXX
#define _SDXMLIMP_IMPL_HXX

#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif

#ifndef _XMLOFF_XMLTKMAP_HXX
#include "xmltkmap.hxx"
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

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

enum SdXMLDocElemTokenMap
{
    XML_TOK_DOC_STYLES,
    XML_TOK_DOC_AUTOSTYLES,
    XML_TOK_DOC_MASTERSTYLES,
    XML_TOK_DOC_META,
    XML_TOK_DOC_BODY,
    XML_TOK_DOC_SCRIPT,
    XML_TOK_DOC_SETTINGS,
    XML_TOK_OFFICE_END = XML_TOK_UNKNOWN
};

enum SdXMLBodyElemTokenMap
{
    XML_TOK_BODY_PAGE,
    XML_TOK_BODY_SETTINGS
};

enum SdXMLStylesElemTokenMap
{
    XML_TOK_STYLES_MASTER_PAGE,
    XML_TOK_STYLES_STYLE,
    XML_TOK_STYLES_PAGE_MASTER,
    XML_TOK_STYLES_PRESENTATION_PAGE_LAYOUT
};

enum SdXMLAutoStylesElemTokenMap
{
    XML_TOK_AUTOSTYLES_STYLE
};

enum SdXMLMasterPageElemTokenMap
{
    XML_TOK_MASTERPAGE_STYLE,
    XML_TOK_MASTERPAGE_NOTES
};

enum SdXMLMasterPageAttrTokenMap
{
    XML_TOK_MASTERPAGE_NAME,
    XML_TOK_MASTERPAGE_DISPLAY_NAME,
    XML_TOK_MASTERPAGE_PAGE_MASTER_NAME,
    XML_TOK_MASTERPAGE_STYLE_NAME,
    XML_TOK_MASTERPAGE_PAGE_LAYOUT_NAME,
    XML_TOK_MASTERPAGE_USE_HEADER_NAME,
    XML_TOK_MASTERPAGE_USE_FOOTER_NAME,
    XML_TOK_MASTERPAGE_USE_DATE_TIME_NAME
};

enum SdXMLPageMasterAttrTokenMap
{
    XML_TOK_PAGEMASTER_NAME
};

enum SdXMLPageMasterStyleAttrTokenMap
{
    XML_TOK_PAGEMASTERSTYLE_MARGIN_TOP,
    XML_TOK_PAGEMASTERSTYLE_MARGIN_BOTTOM,
    XML_TOK_PAGEMASTERSTYLE_MARGIN_LEFT,
    XML_TOK_PAGEMASTERSTYLE_MARGIN_RIGHT,
    XML_TOK_PAGEMASTERSTYLE_PAGE_WIDTH,
    XML_TOK_PAGEMASTERSTYLE_PAGE_HEIGHT,
    XML_TOK_PAGEMASTERSTYLE_PAGE_ORIENTATION
};

enum SdXMLDocStyleAttrTokenMap
{
    XML_TOK_DOCSTYLE_NAME,
    XML_TOK_DOCSTYLE_FAMILY,
    XML_TOK_DOCSTYLE_PARENT_STYLE_NAME,
    XML_TOK_DOCSTYLE_AUTOMATIC
};

enum SdXMLDocStyleElemTokenMap
{
    XML_TOK_DOCSTYLE_PROPERTIES,
    XML_TOK_DOCSTYLE_PRESENTATION_PLACEHOLDER
};

enum SdXMLDrawPageAttrTokenMap
{
    XML_TOK_DRAWPAGE_NAME,
    XML_TOK_DRAWPAGE_STYLE_NAME,
    XML_TOK_DRAWPAGE_MASTER_PAGE_NAME,
    XML_TOK_DRAWPAGE_PAGE_LAYOUT_NAME,
    XML_TOK_DRAWPAGE_ID,
    XML_TOK_DRAWPAGE_HREF,
    XML_TOK_DRAWPAGE_USE_HEADER_NAME,
    XML_TOK_DRAWPAGE_USE_FOOTER_NAME,
    XML_TOK_DRAWPAGE_USE_DATE_TIME_NAME
};

enum SdXMLDrawPageElemTokenMap
{
    XML_TOK_DRAWPAGE_NOTES
};

enum SdXMLPresentationPlaceholderAttrTokenMap
{
    XML_TOK_PRESENTATIONPLACEHOLDER_OBJECTNAME,
    XML_TOK_PRESENTATIONPLACEHOLDER_X,
    XML_TOK_PRESENTATIONPLACEHOLDER_Y,
    XML_TOK_PRESENTATIONPLACEHOLDER_WIDTH,
    XML_TOK_PRESENTATIONPLACEHOLDER_HEIGHT
};

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

struct SdXMLltXDrawPageId
{
  bool operator()(sal_Int32 nId1, sal_Int32 nId2 ) const
  {
    return nId1 < nId2;
  }
};

typedef std::map< sal_Int32, com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage >, SdXMLltXDrawPageId > DrawPageIdMap;

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

class SvXMLUnitConverter;
class SvXMLTokenMap;
class XMLSdPropHdlFactory;
class XMLPropertySetMapper;
class XMLPropStyleContext;
class SdXMLStylesContext;
class SdXMLMasterStylesContext;

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

struct DateTimeDeclContextImpl
{
    rtl::OUString maStrText;
    sal_Bool mbFixed;
    rtl::OUString maStrDateTimeFormat;

    DateTimeDeclContextImpl() : mbFixed(sal_True) {}
};

DECLARE_STL_USTRINGACCESS_MAP( ::rtl::OUString, HeaderFooterDeclMap );
DECLARE_STL_USTRINGACCESS_MAP( DateTimeDeclContextImpl, DateTimeDeclMap );

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

class SdXMLImport: public SvXMLImport
{
    com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > mxDocStyleFamilies;
    com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocMasterPages;
    com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocDrawPages;
    com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > mxPageLayouts;

    // contexts for Style and AutoStyle import
    SdXMLMasterStylesContext*   mpMasterStylesContext;

    // token map lists
    SvXMLTokenMap*              mpDocElemTokenMap;
    SvXMLTokenMap*              mpBodyElemTokenMap;
    SvXMLTokenMap*              mpStylesElemTokenMap;
    SvXMLTokenMap*              mpAutoStylesElemTokenMap;
    SvXMLTokenMap*              mpMasterPageElemTokenMap;
    SvXMLTokenMap*              mpMasterPageAttrTokenMap;
    SvXMLTokenMap*              mpPageMasterAttrTokenMap;
    SvXMLTokenMap*              mpPageMasterStyleAttrTokenMap;
    SvXMLTokenMap*              mpDocStyleAttrTokenMap;
    SvXMLTokenMap*              mpDocStyleElemTokenMap;
    SvXMLTokenMap*              mpDrawPageAttrTokenMap;
    SvXMLTokenMap*              mpDrawPageElemTokenMap;
    SvXMLTokenMap*              mpPresentationPlaceholderAttrTokenMap;

    sal_uInt16                  mnStyleFamilyMask;

    sal_Int32                   mnNewPageCount;
    sal_Int32                   mnNewMasterPageCount;

    sal_Bool                    mbIsDraw;
    sal_Bool                    mbLoadDoc;
    sal_Bool                    mbPreview;

    DrawPageIdMap               maDrawPageIds;

    ::rtl::OUString             msPageLayouts;
    ::rtl::OUString             msPreview;

    HeaderFooterDeclMap         maHeaderDeclsMap;
    HeaderFooterDeclMap         maFooterDeclsMap;
    DateTimeDeclMap             maDateTimeDeclsMap;

protected:
    // This method is called after the namespace map has been updated, but
    // before a context for the current element has been pushed.
    virtual SvXMLImportContext *CreateContext(sal_uInt16 nPrefix,
      const rtl::OUString& rLocalName,
      const com::sun::star::uno::Reference<
        com::sun::star::xml::sax::XAttributeList>& xAttrList);

public:
    // #110680#
    SdXMLImport(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
        sal_Bool bIsDraw, sal_uInt16 nImportFlags = IMPORT_ALL );
    ~SdXMLImport() throw ();

    // XImporter
    virtual void SAL_CALL setTargetDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    // XInitialization
    virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    void SetProgress(sal_Int32 nProg);

    virtual void SetViewSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aViewProps);
    virtual void SetConfigurationSettings(const com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aConfigProps);

    // namespace office
    SvXMLImportContext* CreateMetaContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLImportContext* CreateScriptContext( const ::rtl::OUString& rLocalName );
    SvXMLImportContext* CreateBodyContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLStylesContext* CreateStylesContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLStylesContext* CreateAutoStylesContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);
    SvXMLImportContext* CreateMasterStylesContext(const rtl::OUString& rLocalName,
        const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList);

    // Styles and AutoStyles contexts
    const SdXMLMasterStylesContext* GetMasterStylesContext() const { return mpMasterStylesContext; }

    sal_uInt16 GetStyleFamilyMask() const { return mnStyleFamilyMask; }
    sal_Bool IsStylesOnlyMode() const { return !mbLoadDoc; }

    const SvXMLTokenMap& GetDocElemTokenMap();
    const SvXMLTokenMap& GetBodyElemTokenMap();
    const SvXMLTokenMap& GetStylesElemTokenMap();
    const SvXMLTokenMap& GetMasterPageElemTokenMap();
    const SvXMLTokenMap& GetMasterPageAttrTokenMap();
    const SvXMLTokenMap& GetPageMasterAttrTokenMap();
    const SvXMLTokenMap& GetPageMasterStyleAttrTokenMap();
    const SvXMLTokenMap& GetDrawPageAttrTokenMap();
    const SvXMLTokenMap& GetDrawPageElemTokenMap();
    const SvXMLTokenMap& GetPresentationPlaceholderAttrTokenMap();

    // export local parameters concerning page access and similar
    const com::sun::star::uno::Reference<
        com::sun::star::container::XNameAccess >& GetLocalDocStyleFamilies() const { return mxDocStyleFamilies; }
    const com::sun::star::uno::Reference<
        com::sun::star::container::XIndexAccess >& GetLocalMasterPages() const { return mxDocMasterPages; }
    const com::sun::star::uno::Reference<
        com::sun::star::container::XIndexAccess >& GetLocalDrawPages() const { return mxDocDrawPages; }

    sal_Int32 GetNewPageCount() const { return mnNewPageCount; }
    void IncrementNewPageCount() { mnNewPageCount++; }
    sal_Int32 GetNewMasterPageCount() const { return mnNewMasterPageCount; }
    void IncrementNewMasterPageCount() { mnNewMasterPageCount++; }

    com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > getPageLayouts() const { return mxPageLayouts; }

    sal_Bool IsDraw() const { return mbIsDraw; }
    sal_Bool IsImpress() const { return !mbIsDraw; }

    // import pool defaults. Parameter contains pool defaults read
    // from input data. These data needs to be set at the model.
    void ImportPoolDefaults(const XMLPropStyleContext* pPool);

    void setDrawPageId( sal_Int32 nId, com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > );
    com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > getDrawPageForId( sal_Int32 nId );

    // #80365#
    virtual void SetStatisticAttributes(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs);

    sal_Bool IsPreview() const { return mbPreview; }

    // XServiceInfo ( : SvXMLExport )
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );

    void AddHeaderDecl( const ::rtl::OUString& rName, const ::rtl::OUString& rText );
    void AddFooterDecl( const ::rtl::OUString& rName, const ::rtl::OUString& rText );
    void AddDateTimeDecl( const ::rtl::OUString& rName, const ::rtl::OUString& rText, sal_Bool bFixed, const ::rtl::OUString& rDateTimeFormat );

    ::rtl::OUString GetHeaderDecl( const ::rtl::OUString& rName ) const;
    ::rtl::OUString GetFooterDecl( const ::rtl::OUString& rName ) const;
    ::rtl::OUString GetDateTimeDecl( const ::rtl::OUString& rName, sal_Bool& rbFixed, ::rtl::OUString& rDateTimeFormat );

};

#endif  //  _SDXMLIMP_HXX
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "ResourceFactory.h"
#include "Resources.h"
#include "SkBitmap.h"
#include "SkCommandLineFlags.h"
#include "SkData.h"
#include "SkImage.h"
#include "SkImageGenerator.h"
#include "SkOSFile.h"
#include "SkOSPath.h"
#include "SkStream.h"
#include "SkTypeface.h"

DEFINE_string2(resourcePath, i, "resources", "Directory with test resources: images, fonts, etc.");

sk_sp<SkData> (*gResourceFactory)(const char*) = nullptr;

SkString GetResourcePath(const char* resource) {
    return SkOSPath::Join(FLAGS_resourcePath[0], resource);
}

void SetResourcePath(const char* resource) {
    FLAGS_resourcePath.set(0, resource);
}

bool DecodeDataToBitmap(sk_sp<SkData> data, SkBitmap* dst) {
    std::unique_ptr<SkImageGenerator> gen(SkImageGenerator::MakeFromEncoded(std::move(data)));
    return gen && dst->tryAllocPixels(gen->getInfo()) &&
        gen->getPixels(gen->getInfo().makeColorSpace(nullptr), dst->getPixels(), dst->rowBytes(),
                       nullptr);
}

std::unique_ptr<SkStreamAsset> GetResourceAsStream(const char* resource) {
    auto data = GetResourceAsData(resource);
    return data ? std::unique_ptr<SkStreamAsset>(new SkMemoryStream(std::move(data)))
                : nullptr;
}

sk_sp<SkData> GetResourceAsData(const char* resource) {
    if (sk_sp<SkData> data = gResourceFactory
                           ? gResourceFactory(resource)
                           : SkData::MakeFromFileName(GetResourcePath(resource).c_str())) {
        return data;
    }
    SkDebugf("Resource \"%s\" not found.\n", resource);
    #ifdef SK_TOOLS_REQUIRE_RESOURCES
    SK_ABORT("missing resource");
    #endif
    return nullptr;
}

sk_sp<SkTypeface> MakeResourceAsTypeface(const char* resource) {
    std::unique_ptr<SkStreamAsset> stream(GetResourceAsStream(resource));
    if (!stream) {
        return nullptr;
    }
    return SkTypeface::MakeFromStream(stream.release());
}
<commit_msg>Make missing resource message print the full expected path<commit_after>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "ResourceFactory.h"
#include "Resources.h"
#include "SkBitmap.h"
#include "SkCommandLineFlags.h"
#include "SkData.h"
#include "SkImage.h"
#include "SkImageGenerator.h"
#include "SkOSFile.h"
#include "SkOSPath.h"
#include "SkStream.h"
#include "SkTypeface.h"

DEFINE_string2(resourcePath, i, "resources", "Directory with test resources: images, fonts, etc.");

sk_sp<SkData> (*gResourceFactory)(const char*) = nullptr;

SkString GetResourcePath(const char* resource) {
    return SkOSPath::Join(FLAGS_resourcePath[0], resource);
}

void SetResourcePath(const char* resource) {
    FLAGS_resourcePath.set(0, resource);
}

bool DecodeDataToBitmap(sk_sp<SkData> data, SkBitmap* dst) {
    std::unique_ptr<SkImageGenerator> gen(SkImageGenerator::MakeFromEncoded(std::move(data)));
    return gen && dst->tryAllocPixels(gen->getInfo()) &&
        gen->getPixels(gen->getInfo().makeColorSpace(nullptr), dst->getPixels(), dst->rowBytes(),
                       nullptr);
}

std::unique_ptr<SkStreamAsset> GetResourceAsStream(const char* resource) {
    auto data = GetResourceAsData(resource);
    return data ? std::unique_ptr<SkStreamAsset>(new SkMemoryStream(std::move(data)))
                : nullptr;
}

sk_sp<SkData> GetResourceAsData(const char* resource) {
    if (sk_sp<SkData> data = gResourceFactory
                           ? gResourceFactory(resource)
                           : SkData::MakeFromFileName(GetResourcePath(resource).c_str())) {
        return data;
    }
    SkDebugf("Resource \"%s\" not found.\n", GetResourcePath(resource).c_str());
    #ifdef SK_TOOLS_REQUIRE_RESOURCES
    SK_ABORT("missing resource");
    #endif
    return nullptr;
}

sk_sp<SkTypeface> MakeResourceAsTypeface(const char* resource) {
    std::unique_ptr<SkStreamAsset> stream(GetResourceAsStream(resource));
    if (!stream) {
        return nullptr;
    }
    return SkTypeface::MakeFromStream(stream.release());
}
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Defines a user hook for Geant4 to assign custom track information via TrackInfoG4 objects. This includes custom
 * (unique) track ids.
 * @copyright Copyright (c) 2018 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#ifndef SetTrackInfoUserHookG4_H
#define SetTrackInfoUserHookG4_H 1

#include "G4Track.hh"
#include "G4UserTrackingAction.hh"

#include "TrackInfoManager.hpp"

namespace allpix {
    /**
     * @brief Assigns every G4Track a TrackInfoG4 which carries various inforamtion, including the custom track id
     */
    class SetTrackInfoUserHookG4 : public G4UserTrackingAction {
    public:
        /**
         * @brief Constructor taking a TrackInfoManager*
         * @param track_info_mgr_ptr Pointer to TrackInfoManager which must be used to create the TrackInfoG4 instances
         */
        SetTrackInfoUserHookG4(TrackInfoManager* track_info_mgr_ptr) : track_info_mgr_ptr_(track_info_mgr_ptr){};

        /**
         * @brief Default destructor
         */
        ~SetTrackInfoUserHookG4() = default;

        /**
         * @brief Called for every G4Track at beginning
         * @param aTrack The pointer to the G4Track for which this routine is called
         */
        void PreUserTrackingAction(const G4Track* aTrack);

        /**
         * @brief Called for every G4Track at end
         * @param aTrack The pointer to the G4Track for which this routine is called
         */
        void PostUserTrackingAction(const G4Track* aTrack);

    private:
        // Raw ptr to track info manager to create instances of TrackInfoG4
        TrackInfoManager* track_info_mgr_ptr_;
    };

} // namespace allpix
#endif
<commit_msg>SetTrackInfoUserActionHook: explic constructor and override functions<commit_after>/**
 * @file
 * @brief Defines a user hook for Geant4 to assign custom track information via TrackInfoG4 objects. This includes custom
 * (unique) track ids.
 * @copyright Copyright (c) 2018 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#ifndef SetTrackInfoUserHookG4_H
#define SetTrackInfoUserHookG4_H 1

#include "G4Track.hh"
#include "G4UserTrackingAction.hh"

#include "TrackInfoManager.hpp"

namespace allpix {
    /**
     * @brief Assigns every G4Track a TrackInfoG4 which carries various inforamtion, including the custom track id
     */
    class SetTrackInfoUserHookG4 : public G4UserTrackingAction {
    public:
        /**
         * @brief Constructor taking a TrackInfoManager*
         * @param track_info_mgr_ptr Pointer to TrackInfoManager which must be used to create the TrackInfoG4 instances
         */
        explicit SetTrackInfoUserHookG4(TrackInfoManager* track_info_mgr_ptr) : track_info_mgr_ptr_(track_info_mgr_ptr){};

        /**
         * @brief Default destructor
         */
        ~SetTrackInfoUserHookG4() override = default;

        /**
         * @brief Called for every G4Track at beginning
         * @param aTrack The pointer to the G4Track for which this routine is called
         */
        void PreUserTrackingAction(const G4Track* aTrack) override;

        /**
         * @brief Called for every G4Track at end
         * @param aTrack The pointer to the G4Track for which this routine is called
         */
        void PostUserTrackingAction(const G4Track* aTrack) override;

    private:
        // Raw ptr to track info manager to create instances of TrackInfoG4
        TrackInfoManager* track_info_mgr_ptr_;
    };

} // namespace allpix
#endif
<|endoftext|>


<commit_before>#include <FWPlatform.h>
#include <EventLoop.h>
#include <CurlClient.h>
#include <Logger.h>
#include <ContextCairo.h>
#include <SDLSoundCanvas.h>
#include <Message.h>
#include <FWApplication.h>

#include <TouchEvent.h>
#include <DrawEvent.h>
#include <SysEvent.h>

#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <cassert>

using namespace std;

class PlatformSDL : public FWPlatform {
public:
  PlatformSDL() : FWPlatform(1.0f,
			     // "#version 300 es",
			     "#version 100",
			     true) { }

  double getTime() const override {
    struct timeval tv;
    struct timezone tz;
    int r = gettimeofday(&tv, &tz);
    double t = 0;
    if (r == 0) {
      t = (double)tv.tv_sec + tv.tv_usec / 1000000.0;
    }
    return t;
  }

  void showMessageBox(const string & title, const string & message) override {
#if 0
    SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_INFORMATION,
			      title.c_str(),
			      message.c_str(),
			      NULL);
#endif
  }
  string getLocalFilename(const char * fn, FileType type) {
    string s = "assets/";
    return s + fn;
  }

  std::shared_ptr<HTTPClientFactory> createHTTPClientFactory() const {
    return std::make_shared<CurlClientFactory>();
  }

  int showActionSheet(const FWRect&, const FWActionSheet&) {
    return 0;
  }

  std::shared_ptr<canvas::ContextFactory> createContextFactory() const {
    return std::shared_ptr<canvas::ContextFactory>(new canvas::CairoContextFactory);
  }

  void sendMessage(const Message & message) override {
    switch (message.getType()) {
    case Message::SET_CAPTION:
      SDL_WM_SetCaption(message.getTextValue().c_str(),
			message.getTextValue().c_str());
      break;
    default:
      break;
    }
  }

  std::shared_ptr<SoundCanvas> createSoundCanvas() const override {
    return std::make_shared<SDLSoundCanvas>();
  }

  std::shared_ptr<Logger> createLogger() const override {
    return std::make_shared<BasicLogger>();
  }

  // std::shared_ptr<EventLoop> createEventLoop() override;

  std::string showTextEntryDialog(const std::string & message) {
    return "";
  }

  std::string getBundleFilename(const char * filename) {
    string s = "assets/";
    return s + filename;
  }

  void storeValue(const std::string & key, const std::string & value) {

  }

  std::string loadValue(const std::string & key) {
    return "";
  }

  void swapBuffers() {
    SDL_GL_SwapBuffers( );
  }

  void run() {
    SDL_Event event;

    cerr << "starting runloop\n";

    while ( true ) {
      /* Grab all the events off the queue. */
      while( SDL_PollEvent( &event ) ) {
	switch( event.type ) {
	case SDL_KEYDOWN:
	  /* Handle key presses. */
	  // handle_key_down( &event.key.keysym );
	  break;
	case SDL_MOUSEBUTTONDOWN:
	  {
	    TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_DOWN, mouse_x, display_height - 1 - mouse_y, getTime(), 0);
	    postEvent(ev);
	    button_pressed = true;
	  }
	  break;
	case SDL_MOUSEBUTTONUP:
	  {
	    TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_UP, mouse_x, display_height - 1 - mouse_y, getTime(), 0);
	    postEvent(ev);
	    button_pressed = false;
	  }
	  break;
	case SDL_MOUSEMOTION:
	  if (button_pressed) {
	    TouchEvent ev(getActiveViewId(), TouchEvent::ACTION_MOVE, event.motion.x, display_height - 1 - event.motion.y, getTime(), 0);
	    postEvent(ev);
	  }
	  mouse_x = event.motion.x;
	  mouse_y = event.motion.y;
	  break;
	case SDL_VIDEORESIZE:
	  {
	    int w = event.resize.w, h = event.resize.h;
	    cerr << "resized (" << w << " " << h << ")\n";
	    setDisplayWidth(w);
	    setDisplayHeight(h);
	    getApplication().getFirstChild()->onResize(w, h, w, h);
	  }
	  break;
	case SDL_QUIT:
	  return;
	}
      }

      getApplication().loadEvents();

      if (getApplication().getFirstChild()->onUpdate(getTime())) {
	DrawEvent ev(getActiveViewId());
	postEvent(ev);
	swapBuffers();
      }
    }
  }

private:
  bool button_pressed = false;
  int mouse_x = 0, mouse_y = 0;
};

#if 0
static void handle_key_down(SDL_keysym* keysym) {

    /*
     * We're only interested if 'Esc' has
     * been presssed.
     *
     * EXERCISE:
     * Handle the arrow keys and have that change the
     * viewing position/angle.
     */
    switch( keysym->sym ) {
    case SDLK_ESCAPE:
        quit_tutorial( 0 );
        break;
    case SDLK_SPACE:
        should_rotate = !should_rotate;
        break;
    default:
        break;
    }

}
#endif

extern FWApplication * applicationMain();

int main(int argc, char *argv[]) {
  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 ) {
    /* Failed, exit. */
    fprintf( stderr, "Video initialization failed: %s\n",
             SDL_GetError( ) );
    SDL_Quit( );
    exit(1);
  }

  const SDL_VideoInfo * info = SDL_GetVideoInfo( );

  if (!info) {
    /* This should probably never happen. */
    fprintf( stderr, "Video query failed: %s\n", SDL_GetError() );
    SDL_Quit();
    exit(1);
  }

  int width = 800, height = 600;
  int bpp = info->vfmt->BitsPerPixel;

  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

  int flags = SDL_OPENGL; // | SDL_FULLSCREEN;

  if (SDL_SetVideoMode( width, height, bpp, flags ) == 0) {
    fprintf( stderr, "Video mode set failed: %s\n",
             SDL_GetError( ) );
    SDL_Quit();
    exit(1);
  }

  FWApplication * application = applicationMain();

  cerr << "starting, app = " << application << "\n";

  PlatformSDL platform;
  platform.setApplication(application);
  platform.getApplication().initialize(&platform);
  platform.getApplication().onCmdLine(argc, argv);

  platform.setDisplayWidth(width);
  platform.setDisplayHeight(height);
  platform.getApplication().initializeContent();

  platform.run();

#if 0
  auto eventloop = platform.createEventLoop();
  eventloop->run();
#endif

  SysEvent ev(0, SysEvent::SHUTDOWN);
  ev.dispatch(platform.getApplication());
  SDL_Quit();
  return 0;
}
<commit_msg>send internal element id as a parameter to postEvent<commit_after>#include <FWPlatform.h>
#include <EventLoop.h>
#include <CurlClient.h>
#include <Logger.h>
#include <ContextCairo.h>
#include <SDLSoundCanvas.h>
#include <Message.h>
#include <FWApplication.h>

#include <TouchEvent.h>
#include <DrawEvent.h>
#include <SysEvent.h>

#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <cassert>

using namespace std;

class PlatformSDL : public FWPlatform {
public:
  PlatformSDL() : FWPlatform(1.0f,
			     // "#version 300 es",
			     "#version 100",
			     true) { }

  double getTime() const override {
    struct timeval tv;
    struct timezone tz;
    int r = gettimeofday(&tv, &tz);
    double t = 0;
    if (r == 0) {
      t = (double)tv.tv_sec + tv.tv_usec / 1000000.0;
    }
    return t;
  }

  void showMessageBox(const string & title, const string & message) override {
#if 0
    SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_INFORMATION,
			      title.c_str(),
			      message.c_str(),
			      NULL);
#endif
  }
  string getLocalFilename(const char * fn, FileType type) {
    string s = "assets/";
    return s + fn;
  }

  std::shared_ptr<HTTPClientFactory> createHTTPClientFactory() const {
    return std::make_shared<CurlClientFactory>();
  }

  int showActionSheet(const FWRect&, const FWActionSheet&) {
    return 0;
  }

  std::shared_ptr<canvas::ContextFactory> createContextFactory() const {
    return std::shared_ptr<canvas::ContextFactory>(new canvas::CairoContextFactory);
  }

  void sendMessage(const Message & message) override {
    switch (message.getType()) {
    case Message::SET_CAPTION:
      SDL_WM_SetCaption(message.getTextValue().c_str(),
			message.getTextValue().c_str());
      break;
    default:
      break;
    }
  }

  std::shared_ptr<SoundCanvas> createSoundCanvas() const override {
    return std::make_shared<SDLSoundCanvas>();
  }

  std::shared_ptr<Logger> createLogger() const override {
    return std::make_shared<BasicLogger>();
  }

  // std::shared_ptr<EventLoop> createEventLoop() override;

  std::string showTextEntryDialog(const std::string & message) {
    return "";
  }

  std::string getBundleFilename(const char * filename) {
    string s = "assets/";
    return s + filename;
  }

  void storeValue(const std::string & key, const std::string & value) {

  }

  std::string loadValue(const std::string & key) {
    return "";
  }

  void swapBuffers() {
    SDL_GL_SwapBuffers( );
  }

  void run() {
    SDL_Event event;

    cerr << "starting runloop\n";

    while ( true ) {
      /* Grab all the events off the queue. */
      while( SDL_PollEvent( &event ) ) {
	switch( event.type ) {
	case SDL_KEYDOWN:
	  /* Handle key presses. */
	  // handle_key_down( &event.key.keysym );
	  break;
	case SDL_MOUSEBUTTONDOWN:
	  {
	    TouchEvent ev(TouchEvent::ACTION_DOWN, mouse_x, display_height - 1 - mouse_y, getTime(), 0);
	    postEvent(getActiveViewId(), ev);
	    button_pressed = true;
	  }
	  break;
	case SDL_MOUSEBUTTONUP:
	  {
	    TouchEvent ev(TouchEvent::ACTION_UP, mouse_x, display_height - 1 - mouse_y, getTime(), 0);
	    postEvent(getActiveViewId(), ev);
	    button_pressed = false;
	  }
	  break;
	case SDL_MOUSEMOTION:
	  if (button_pressed) {
	    TouchEvent ev(TouchEvent::ACTION_MOVE, event.motion.x, display_height - 1 - event.motion.y, getTime(), 0);
	    postEvent(getActiveViewId(), ev);
	  }
	  mouse_x = event.motion.x;
	  mouse_y = event.motion.y;
	  break;
	case SDL_VIDEORESIZE:
	  {
	    int w = event.resize.w, h = event.resize.h;
	    cerr << "resized (" << w << " " << h << ")\n";
	    setDisplayWidth(w);
	    setDisplayHeight(h);
	    getApplication().getFirstChild()->onResize(w, h, w, h);
	  }
	  break;
	case SDL_QUIT:
	  return;
	}
      }

      getApplication().loadEvents();

      if (getApplication().getFirstChild()->onUpdate(getTime())) {
	DrawEvent ev;
	postEvent(getActiveViewId(), ev);
	swapBuffers();
      }
    }
  }

private:
  bool button_pressed = false;
  int mouse_x = 0, mouse_y = 0;
};

#if 0
static void handle_key_down(SDL_keysym* keysym) {

    /*
     * We're only interested if 'Esc' has
     * been presssed.
     *
     * EXERCISE:
     * Handle the arrow keys and have that change the
     * viewing position/angle.
     */
    switch( keysym->sym ) {
    case SDLK_ESCAPE:
        quit_tutorial( 0 );
        break;
    case SDLK_SPACE:
        should_rotate = !should_rotate;
        break;
    default:
        break;
    }

}
#endif

extern FWApplication * applicationMain();

int main(int argc, char *argv[]) {
  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 ) {
    /* Failed, exit. */
    fprintf( stderr, "Video initialization failed: %s\n",
             SDL_GetError( ) );
    SDL_Quit( );
    exit(1);
  }

  const SDL_VideoInfo * info = SDL_GetVideoInfo( );

  if (!info) {
    /* This should probably never happen. */
    fprintf( stderr, "Video query failed: %s\n", SDL_GetError() );
    SDL_Quit();
    exit(1);
  }

  int width = 800, height = 600;
  int bpp = info->vfmt->BitsPerPixel;

  SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

  int flags = SDL_OPENGL; // | SDL_FULLSCREEN;

  if (SDL_SetVideoMode( width, height, bpp, flags ) == 0) {
    fprintf( stderr, "Video mode set failed: %s\n",
             SDL_GetError( ) );
    SDL_Quit();
    exit(1);
  }

  FWApplication * application = applicationMain();

  cerr << "starting, app = " << application << "\n";

  PlatformSDL platform;
  platform.setApplication(application);
  platform.getApplication().initialize(&platform);
  platform.getApplication().onCmdLine(argc, argv);

  platform.setDisplayWidth(width);
  platform.setDisplayHeight(height);
  platform.getApplication().initializeContent();

  platform.run();

#if 0
  auto eventloop = platform.createEventLoop();
  eventloop->run();
#endif

  SysEvent ev(0, SysEvent::SHUTDOWN);
  ev.dispatch(platform.getApplication());
  SDL_Quit();
  return 0;
}
<|endoftext|>


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

// Author: matterbury@google.com (Matt Atterbury)

#include "net/instaweb/rewriter/public/local_storage_cache_filter.h"

#include <set>

#include "base/logging.h"
#include "net/instaweb/htmlparse/public/html_element.h"
#include "net/instaweb/htmlparse/public/html_name.h"
#include "net/instaweb/htmlparse/public/html_node.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/request_headers.h"
#include "net/instaweb/rewriter/cached_result.pb.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/static_asset_manager.h"
#include "net/instaweb/util/public/escaping.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/hasher.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/time_util.h"

namespace net_instaweb {

const char LocalStorageCacheFilter::kLscCookieName[] = "_GPSLSC";
const char LocalStorageCacheFilter::kLscInitializer[] =
    "pagespeed.localStorageCacheInit();";

const char LocalStorageCacheFilter::kCandidatesFound[] =
    "num_local_storage_cache_candidates_found";
const char LocalStorageCacheFilter::kStoredTotal[] =
    "num_local_storage_cache_stored_total";
const char LocalStorageCacheFilter::kStoredImages[] =
    "num_local_storage_cache_stored_images";
const char LocalStorageCacheFilter::kStoredCss[] =
    "num_local_storage_cache_stored_css";
const char LocalStorageCacheFilter::kCandidatesAdded[] =
    "num_local_storage_cache_candidates_added";
const char LocalStorageCacheFilter::kCandidatesRemoved[] =
    "num_local_storage_cache_candidates_removed";

LocalStorageCacheFilter::LocalStorageCacheFilter(RewriteDriver* rewrite_driver)
    : RewriteFilter(rewrite_driver),
      script_inserted_(false),
      script_needs_inserting_(false) {
  Statistics* stats = server_context_->statistics();
  num_local_storage_cache_candidates_found_ =
      stats->GetVariable(kCandidatesFound);
  num_local_storage_cache_stored_total_ =
      stats->GetVariable(kStoredTotal);
  num_local_storage_cache_stored_images_ =
      stats->GetVariable(kStoredImages);
  num_local_storage_cache_stored_css_ =
      stats->GetVariable(kStoredCss);
  num_local_storage_cache_candidates_added_ =
      stats->GetVariable(kCandidatesAdded);
  num_local_storage_cache_candidates_removed_ =
      stats->GetVariable(kCandidatesRemoved);
}

LocalStorageCacheFilter::~LocalStorageCacheFilter() {
  cookie_hashes_.clear();
}

void LocalStorageCacheFilter::InitStats(Statistics* statistics) {
  statistics->AddVariable(LocalStorageCacheFilter::kCandidatesFound);
  statistics->AddVariable(LocalStorageCacheFilter::kStoredTotal);
  statistics->AddVariable(LocalStorageCacheFilter::kStoredImages);
  statistics->AddVariable(LocalStorageCacheFilter::kStoredCss);
  statistics->AddVariable(LocalStorageCacheFilter::kCandidatesAdded);
  statistics->AddVariable(LocalStorageCacheFilter::kCandidatesRemoved);
}

void LocalStorageCacheFilter::StartDocumentImpl() {
  script_inserted_ = false;
  script_needs_inserting_ = false;
}

void LocalStorageCacheFilter::EndDocument() {
  cookie_hashes_.clear();
}

void LocalStorageCacheFilter::StartElementImpl(HtmlElement* element) {
  // The css_inline_filter and image_rewrite_filter can add the LSC URL to
  // the inlined resource, indicating that we have to insert our JS for them.
  if (element->keyword() == HtmlName::kImg ||
      element->keyword() == HtmlName::kLink) {
    if (element->AttributeValue(HtmlName::kPagespeedLscUrl) != NULL) {
      // Note that we might end up not needing the inserted script because
      // the img/link might not be able to be inlined. So be it.
      script_needs_inserting_ = true;
    }
  }

  // We need to insert our javascript before the first element that uses it.
  if (script_needs_inserting_  && !script_inserted_) {
    InsertOurScriptElement(element);
  }
}

void LocalStorageCacheFilter::EndElementImpl(HtmlElement* element) {
  // An <img> or <link> that has a pagespeed_lsc_url attribute, and whose
  // URL's hash is in the LSC cookie, needs to be replaced by a JS snippet.
  bool is_img = false;
  bool is_link = false;
  if (element->keyword() == HtmlName::kImg) {
    is_img = true;
  } else if (element->keyword() == HtmlName::kLink) {
    is_link = true;
  }
  if (is_img || is_link) {
    const char* url = element->AttributeValue(HtmlName::kPagespeedLscUrl);
    if (url != NULL) {
      num_local_storage_cache_candidates_found_->Add(1);
      GoogleString hash = driver_->server_context()->hasher()->Hash(url);
      if (IsHashInCookie(driver_, kLscCookieName, hash, &cookie_hashes_)) {
        num_local_storage_cache_stored_total_->Add(1);
        StringPiece given_url(url);
        GoogleUrl abs_url(base_url(), given_url);
        StringPiece lsc_url(abs_url.is_valid() ? abs_url.Spec() : given_url);
        GoogleString snippet("pagespeed.localStorageCache.");
        if (is_img) {
          num_local_storage_cache_stored_images_->Add(1);
          StrAppend(&snippet, "inlineImg(\"", lsc_url, "\"",
                    ExtractOtherImgAttributes(element), ");");
        } else /* is_link */ {
          num_local_storage_cache_stored_css_->Add(1);
          StrAppend(&snippet, "inlineCss(\"", lsc_url, "\");");
        }
        HtmlElement* script_element =
            driver_->NewElement(element->parent(), HtmlName::kScript);
        script_element->AddAttribute(
            driver_->MakeName(HtmlName::kPagespeedNoDefer), NULL,
                              HtmlElement::NO_QUOTE);
        if (driver_->ReplaceNode(element, script_element)) {
          driver_->AppendChild(script_element,
                               driver_->NewCharactersNode(element, snippet));
        }
      }
    }
  }
}

void LocalStorageCacheFilter::InsertOurScriptElement(HtmlElement* before) {
  StaticAssetManager* static_asset_manager =
      driver_->server_context()->static_asset_manager();
  StringPiece local_storage_cache_js =
      static_asset_manager->GetAsset(
          StaticAssetManager::kLocalStorageCacheJs, driver_->options());
  const GoogleString& initialized_js = StrCat(local_storage_cache_js,
                                              kLscInitializer);
  HtmlElement* script_element = driver_->NewElement(before->parent(),
                                                    HtmlName::kScript);
  driver_->InsertElementBeforeElement(before, script_element);
  static_asset_manager->AddJsToElement(initialized_js, script_element, driver_);
  script_element->AddAttribute(driver_->MakeName(HtmlName::kPagespeedNoDefer),
                               NULL, HtmlElement::NO_QUOTE);
  script_inserted_ = true;
}

bool LocalStorageCacheFilter::AddStorableResource(const StringPiece& url,
                                                  RewriteDriver* driver,
                                                  bool skip_cookie_check,
                                                  HtmlElement* element,
                                                  InlineState* state) {
  // Only determine the state once.
  if (!state->initialized_) {
    // If LSC isn't enabled, we're done.
    state->enabled_ =
        driver->options()->Enabled(RewriteOptions::kLocalStorageCache);

    // Get the absolute LSC url from the link url if it's valid otherwise as-is.
    if (state->enabled_) {
      GoogleUrl gurl(driver->base_url(), url);
      StringPiece best_url(gurl.is_valid() ? gurl.Spec() : url);
      best_url.CopyToString(&state->url_);
    }

    state->initialized_ = true;
  }

  if (!state->enabled_) {
    return false;
  }

  // If we've been told to skip the cookie then mark the element regardless,
  // otherwise we need to check if the hash of the url is in the LSC cookie.
  bool add_the_attr = skip_cookie_check;
  if (!skip_cookie_check) {
    RewriteFilter* filter =
        driver->FindFilter(RewriteOptions::kLocalStorageCacheId);
    if (filter != NULL) {
      LocalStorageCacheFilter* lsc =
          static_cast<LocalStorageCacheFilter*>(filter);
      GoogleString hash =
          driver->server_context()->hasher()->Hash(state->url_);
      add_the_attr = IsHashInCookie(driver, kLscCookieName, hash,
                                    lsc->mutable_cookie_hashes());
    }
  }

  // If necessary, set the pagespeed_lsc_url attribute in the element, which
  // later triggers the LSC filter to replace element with JS.
  if (add_the_attr) {
    driver->AddAttribute(element, HtmlName::kPagespeedLscUrl, state->url_);
  }

  return add_the_attr;
}

bool LocalStorageCacheFilter::AddLscAttributes(const StringPiece url,
                                               const CachedResult& cached,
                                               RewriteDriver* driver,
                                               HtmlElement* element) {
  if (!driver->options()->Enabled(RewriteOptions::kLocalStorageCache)) {
    return false;
  }

  // Don't add the other attributes if we don't have a pagespeed_lsc_url.
  if (element->AttributeValue(HtmlName::kPagespeedLscUrl) == NULL) {
    return false;
  }

  // TODO(matterbury): Determine how expensive this is and drop it if too high.
  RewriteFilter* filter =
      driver->FindFilter(RewriteOptions::kLocalStorageCacheId);
  if (filter != NULL) {
    LocalStorageCacheFilter* lsc =
        static_cast<LocalStorageCacheFilter*>(filter);
    lsc->num_local_storage_cache_candidates_added_->Add(1);
  }

  GoogleUrl gurl(driver->base_url(), url);
  StringPiece lsc_url(gurl.is_valid() ? gurl.Spec() : url);
  GoogleString hash = driver->server_context()->hasher()->Hash(lsc_url);
  driver->AddAttribute(element, HtmlName::kPagespeedLscHash, hash);
  if (cached.input_size() > 0) {
    const InputInfo& input_info = cached.input(0);
    if (input_info.has_expiration_time_ms()) {
      GoogleString expiry;
      if (ConvertTimeToString(input_info.expiration_time_ms(), &expiry)) {
        driver->AddAttribute(element, HtmlName::kPagespeedLscExpiry, expiry);
      }
    }
  }

  return true;
}

void LocalStorageCacheFilter::RemoveLscAttributes(HtmlElement* element,
                                                  RewriteDriver* driver) {
  element->DeleteAttribute(HtmlName::kPagespeedLscUrl);
  element->DeleteAttribute(HtmlName::kPagespeedLscHash);
  element->DeleteAttribute(HtmlName::kPagespeedLscExpiry);
  element->DeleteAttribute(HtmlName::kPagespeedNoDefer);

  RewriteFilter* filter =
      driver->FindFilter(RewriteOptions::kLocalStorageCacheId);
  if (filter != NULL) {
    LocalStorageCacheFilter* lsc =
        static_cast<LocalStorageCacheFilter*>(filter);
    lsc->num_local_storage_cache_candidates_removed_->Add(1);
  }
}

bool LocalStorageCacheFilter::IsHashInCookie(const RewriteDriver* driver,
                                             const StringPiece cookie_name,
                                             const StringPiece hash,
                                             std::set<StringPiece>* hash_set) {
  if (driver->request_headers() == NULL) {
    LOG(WARNING) << "LocalStorageCacheFilter::IsHashInCookie: NO HEADERS!";
    return false;
  }

  // If we have a cookie header and we haven't yet parsed it.
  if (hash_set->empty()) {
    ConstStringStarVector v;
    if (driver->request_headers()->Lookup(HttpAttributes::kCookie, &v)) {
      GoogleString prefix;
      StrAppend(&prefix, cookie_name, "=");
      for (int i = 0, nv = v.size(); i < nv; ++i) {
        StringPieceVector cookie_vector;
        SplitStringPieceToVector(*(v[i]), ";", &cookie_vector, true);
        for (int j = 0, nc = cookie_vector.size(); j < nc; ++j) {
          StringPiece cookie(cookie_vector[j]);
          TrimQuote(&cookie);
          if (StringCaseStartsWith(cookie, prefix)) {
            cookie.remove_prefix(prefix.length());
            StringPieceVector hashes;
            SplitStringPieceToVector(cookie, "!", &hashes, true /*omit empty*/);
            for (int k = 0, nh = hashes.size(); k < nh; ++k) {
              hash_set->insert(hashes[k]);
            }
            break;
          }
        }
      }
    }
    // If the named cookie isn't set, store a sentinel to prevent us from
    // checking again pointlessly next time we're called.
    if (hash_set->empty()) {
      hash_set->insert(StringPiece());
    }
  }
  return (hash_set->find(hash) != hash_set->end());
}

GoogleString LocalStorageCacheFilter::ExtractOtherImgAttributes(
    const HtmlElement* element) {
  // Copy over all the 'other' attributes from an img element except for
  // pagespeed_lsc_url, pagespeed_lsc_hash, pagespeed_lsc_expiry,
  // pagespeed_no_defer, and src.
  GoogleString result;
  const HtmlElement::AttributeList& attrs = element->attributes();
  for (HtmlElement::AttributeConstIterator i(attrs.begin());
       i != attrs.end(); ++i) {
    const HtmlElement::Attribute& attr = *i;
    HtmlName::Keyword keyword = attr.keyword();
    if (keyword != HtmlName::kPagespeedLscUrl &&
        keyword != HtmlName::kPagespeedLscHash &&
        keyword != HtmlName::kPagespeedLscExpiry &&
        keyword != HtmlName::kPagespeedNoDefer &&
        keyword != HtmlName::kSrc) {
      GoogleString escaped_js;
      // Escape problematic characters but don't quote it as we do that.
      if (attr.DecodedValueOrNull() != NULL) {
        EscapeToJsStringLiteral(attr.DecodedValueOrNull(), false, &escaped_js);
      }
      StrAppend(&result, ", \"", attr.name_str(), "=", escaped_js, "\"");
    }
  }
  return result;
}

}  // namespace net_instaweb
<commit_msg>Fix the local storage filter to only remove attributes when it is enabled. Also, don't delete pagespeed_no_defer in this case.<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Author: matterbury@google.com (Matt Atterbury)

#include "net/instaweb/rewriter/public/local_storage_cache_filter.h"

#include <set>

#include "base/logging.h"
#include "net/instaweb/htmlparse/public/html_element.h"
#include "net/instaweb/htmlparse/public/html_name.h"
#include "net/instaweb/htmlparse/public/html_node.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/request_headers.h"
#include "net/instaweb/rewriter/cached_result.pb.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/static_asset_manager.h"
#include "net/instaweb/util/public/escaping.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/hasher.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/time_util.h"

namespace net_instaweb {

const char LocalStorageCacheFilter::kLscCookieName[] = "_GPSLSC";
const char LocalStorageCacheFilter::kLscInitializer[] =
    "pagespeed.localStorageCacheInit();";

const char LocalStorageCacheFilter::kCandidatesFound[] =
    "num_local_storage_cache_candidates_found";
const char LocalStorageCacheFilter::kStoredTotal[] =
    "num_local_storage_cache_stored_total";
const char LocalStorageCacheFilter::kStoredImages[] =
    "num_local_storage_cache_stored_images";
const char LocalStorageCacheFilter::kStoredCss[] =
    "num_local_storage_cache_stored_css";
const char LocalStorageCacheFilter::kCandidatesAdded[] =
    "num_local_storage_cache_candidates_added";
const char LocalStorageCacheFilter::kCandidatesRemoved[] =
    "num_local_storage_cache_candidates_removed";

LocalStorageCacheFilter::LocalStorageCacheFilter(RewriteDriver* rewrite_driver)
    : RewriteFilter(rewrite_driver),
      script_inserted_(false),
      script_needs_inserting_(false) {
  Statistics* stats = server_context_->statistics();
  num_local_storage_cache_candidates_found_ =
      stats->GetVariable(kCandidatesFound);
  num_local_storage_cache_stored_total_ =
      stats->GetVariable(kStoredTotal);
  num_local_storage_cache_stored_images_ =
      stats->GetVariable(kStoredImages);
  num_local_storage_cache_stored_css_ =
      stats->GetVariable(kStoredCss);
  num_local_storage_cache_candidates_added_ =
      stats->GetVariable(kCandidatesAdded);
  num_local_storage_cache_candidates_removed_ =
      stats->GetVariable(kCandidatesRemoved);
}

LocalStorageCacheFilter::~LocalStorageCacheFilter() {
  cookie_hashes_.clear();
}

void LocalStorageCacheFilter::InitStats(Statistics* statistics) {
  statistics->AddVariable(LocalStorageCacheFilter::kCandidatesFound);
  statistics->AddVariable(LocalStorageCacheFilter::kStoredTotal);
  statistics->AddVariable(LocalStorageCacheFilter::kStoredImages);
  statistics->AddVariable(LocalStorageCacheFilter::kStoredCss);
  statistics->AddVariable(LocalStorageCacheFilter::kCandidatesAdded);
  statistics->AddVariable(LocalStorageCacheFilter::kCandidatesRemoved);
}

void LocalStorageCacheFilter::StartDocumentImpl() {
  script_inserted_ = false;
  script_needs_inserting_ = false;
}

void LocalStorageCacheFilter::EndDocument() {
  cookie_hashes_.clear();
}

void LocalStorageCacheFilter::StartElementImpl(HtmlElement* element) {
  // The css_inline_filter and image_rewrite_filter can add the LSC URL to
  // the inlined resource, indicating that we have to insert our JS for them.
  if (element->keyword() == HtmlName::kImg ||
      element->keyword() == HtmlName::kLink) {
    if (element->AttributeValue(HtmlName::kPagespeedLscUrl) != NULL) {
      // Note that we might end up not needing the inserted script because
      // the img/link might not be able to be inlined. So be it.
      script_needs_inserting_ = true;
    }
  }

  // We need to insert our javascript before the first element that uses it.
  if (script_needs_inserting_  && !script_inserted_) {
    InsertOurScriptElement(element);
  }
}

void LocalStorageCacheFilter::EndElementImpl(HtmlElement* element) {
  // An <img> or <link> that has a pagespeed_lsc_url attribute, and whose
  // URL's hash is in the LSC cookie, needs to be replaced by a JS snippet.
  bool is_img = false;
  bool is_link = false;
  if (element->keyword() == HtmlName::kImg) {
    is_img = true;
  } else if (element->keyword() == HtmlName::kLink) {
    is_link = true;
  }
  if (is_img || is_link) {
    const char* url = element->AttributeValue(HtmlName::kPagespeedLscUrl);
    if (url != NULL) {
      num_local_storage_cache_candidates_found_->Add(1);
      GoogleString hash = driver_->server_context()->hasher()->Hash(url);
      if (IsHashInCookie(driver_, kLscCookieName, hash, &cookie_hashes_)) {
        num_local_storage_cache_stored_total_->Add(1);
        StringPiece given_url(url);
        GoogleUrl abs_url(base_url(), given_url);
        StringPiece lsc_url(abs_url.is_valid() ? abs_url.Spec() : given_url);
        GoogleString snippet("pagespeed.localStorageCache.");
        if (is_img) {
          num_local_storage_cache_stored_images_->Add(1);
          StrAppend(&snippet, "inlineImg(\"", lsc_url, "\"",
                    ExtractOtherImgAttributes(element), ");");
        } else /* is_link */ {
          num_local_storage_cache_stored_css_->Add(1);
          StrAppend(&snippet, "inlineCss(\"", lsc_url, "\");");
        }
        HtmlElement* script_element =
            driver_->NewElement(element->parent(), HtmlName::kScript);
        script_element->AddAttribute(
            driver_->MakeName(HtmlName::kPagespeedNoDefer), NULL,
                              HtmlElement::NO_QUOTE);
        if (driver_->ReplaceNode(element, script_element)) {
          driver_->AppendChild(script_element,
                               driver_->NewCharactersNode(element, snippet));
        }
      }
    }
  }
}

void LocalStorageCacheFilter::InsertOurScriptElement(HtmlElement* before) {
  StaticAssetManager* static_asset_manager =
      driver_->server_context()->static_asset_manager();
  StringPiece local_storage_cache_js =
      static_asset_manager->GetAsset(
          StaticAssetManager::kLocalStorageCacheJs, driver_->options());
  const GoogleString& initialized_js = StrCat(local_storage_cache_js,
                                              kLscInitializer);
  HtmlElement* script_element = driver_->NewElement(before->parent(),
                                                    HtmlName::kScript);
  driver_->InsertElementBeforeElement(before, script_element);
  static_asset_manager->AddJsToElement(initialized_js, script_element, driver_);
  script_element->AddAttribute(driver_->MakeName(HtmlName::kPagespeedNoDefer),
                               NULL, HtmlElement::NO_QUOTE);
  script_inserted_ = true;
}

bool LocalStorageCacheFilter::AddStorableResource(const StringPiece& url,
                                                  RewriteDriver* driver,
                                                  bool skip_cookie_check,
                                                  HtmlElement* element,
                                                  InlineState* state) {
  // Only determine the state once.
  if (!state->initialized_) {
    // If LSC isn't enabled, we're done.
    state->enabled_ =
        driver->options()->Enabled(RewriteOptions::kLocalStorageCache);

    // Get the absolute LSC url from the link url if it's valid otherwise as-is.
    if (state->enabled_) {
      GoogleUrl gurl(driver->base_url(), url);
      StringPiece best_url(gurl.is_valid() ? gurl.Spec() : url);
      best_url.CopyToString(&state->url_);
    }

    state->initialized_ = true;
  }

  if (!state->enabled_) {
    return false;
  }

  // If we've been told to skip the cookie then mark the element regardless,
  // otherwise we need to check if the hash of the url is in the LSC cookie.
  bool add_the_attr = skip_cookie_check;
  if (!skip_cookie_check) {
    RewriteFilter* filter =
        driver->FindFilter(RewriteOptions::kLocalStorageCacheId);
    if (filter != NULL) {
      LocalStorageCacheFilter* lsc =
          static_cast<LocalStorageCacheFilter*>(filter);
      GoogleString hash =
          driver->server_context()->hasher()->Hash(state->url_);
      add_the_attr = IsHashInCookie(driver, kLscCookieName, hash,
                                    lsc->mutable_cookie_hashes());
    }
  }

  // If necessary, set the pagespeed_lsc_url attribute in the element, which
  // later triggers the LSC filter to replace element with JS.
  if (add_the_attr) {
    driver->AddAttribute(element, HtmlName::kPagespeedLscUrl, state->url_);
  }

  return add_the_attr;
}

bool LocalStorageCacheFilter::AddLscAttributes(const StringPiece url,
                                               const CachedResult& cached,
                                               RewriteDriver* driver,
                                               HtmlElement* element) {
  if (!driver->options()->Enabled(RewriteOptions::kLocalStorageCache)) {
    return false;
  }

  // Don't add the other attributes if we don't have a pagespeed_lsc_url.
  if (element->AttributeValue(HtmlName::kPagespeedLscUrl) == NULL) {
    return false;
  }

  // TODO(matterbury): Determine how expensive this is and drop it if too high.
  RewriteFilter* filter =
      driver->FindFilter(RewriteOptions::kLocalStorageCacheId);
  if (filter != NULL) {
    LocalStorageCacheFilter* lsc =
        static_cast<LocalStorageCacheFilter*>(filter);
    lsc->num_local_storage_cache_candidates_added_->Add(1);
  }

  GoogleUrl gurl(driver->base_url(), url);
  StringPiece lsc_url(gurl.is_valid() ? gurl.Spec() : url);
  GoogleString hash = driver->server_context()->hasher()->Hash(lsc_url);
  driver->AddAttribute(element, HtmlName::kPagespeedLscHash, hash);
  if (cached.input_size() > 0) {
    const InputInfo& input_info = cached.input(0);
    if (input_info.has_expiration_time_ms()) {
      GoogleString expiry;
      if (ConvertTimeToString(input_info.expiration_time_ms(), &expiry)) {
        driver->AddAttribute(element, HtmlName::kPagespeedLscExpiry, expiry);
      }
    }
  }

  return true;
}

void LocalStorageCacheFilter::RemoveLscAttributes(HtmlElement* element,
                                                  RewriteDriver* driver) {
  if (!driver->options()->Enabled(RewriteOptions::kLocalStorageCache)) {
    return;
  }
  element->DeleteAttribute(HtmlName::kPagespeedLscUrl);
  element->DeleteAttribute(HtmlName::kPagespeedLscHash);
  element->DeleteAttribute(HtmlName::kPagespeedLscExpiry);

  RewriteFilter* filter =
      driver->FindFilter(RewriteOptions::kLocalStorageCacheId);
  if (filter != NULL) {
    LocalStorageCacheFilter* lsc =
        static_cast<LocalStorageCacheFilter*>(filter);
    lsc->num_local_storage_cache_candidates_removed_->Add(1);
  }
}

bool LocalStorageCacheFilter::IsHashInCookie(const RewriteDriver* driver,
                                             const StringPiece cookie_name,
                                             const StringPiece hash,
                                             std::set<StringPiece>* hash_set) {
  if (driver->request_headers() == NULL) {
    LOG(WARNING) << "LocalStorageCacheFilter::IsHashInCookie: NO HEADERS!";
    return false;
  }

  // If we have a cookie header and we haven't yet parsed it.
  if (hash_set->empty()) {
    ConstStringStarVector v;
    if (driver->request_headers()->Lookup(HttpAttributes::kCookie, &v)) {
      GoogleString prefix;
      StrAppend(&prefix, cookie_name, "=");
      for (int i = 0, nv = v.size(); i < nv; ++i) {
        StringPieceVector cookie_vector;
        SplitStringPieceToVector(*(v[i]), ";", &cookie_vector, true);
        for (int j = 0, nc = cookie_vector.size(); j < nc; ++j) {
          StringPiece cookie(cookie_vector[j]);
          TrimQuote(&cookie);
          if (StringCaseStartsWith(cookie, prefix)) {
            cookie.remove_prefix(prefix.length());
            StringPieceVector hashes;
            SplitStringPieceToVector(cookie, "!", &hashes, true /*omit empty*/);
            for (int k = 0, nh = hashes.size(); k < nh; ++k) {
              hash_set->insert(hashes[k]);
            }
            break;
          }
        }
      }
    }
    // If the named cookie isn't set, store a sentinel to prevent us from
    // checking again pointlessly next time we're called.
    if (hash_set->empty()) {
      hash_set->insert(StringPiece());
    }
  }
  return (hash_set->find(hash) != hash_set->end());
}

GoogleString LocalStorageCacheFilter::ExtractOtherImgAttributes(
    const HtmlElement* element) {
  // Copy over all the 'other' attributes from an img element except for
  // pagespeed_lsc_url, pagespeed_lsc_hash, pagespeed_lsc_expiry,
  // pagespeed_no_defer, and src.
  GoogleString result;
  const HtmlElement::AttributeList& attrs = element->attributes();
  for (HtmlElement::AttributeConstIterator i(attrs.begin());
       i != attrs.end(); ++i) {
    const HtmlElement::Attribute& attr = *i;
    HtmlName::Keyword keyword = attr.keyword();
    if (keyword != HtmlName::kPagespeedLscUrl &&
        keyword != HtmlName::kPagespeedLscHash &&
        keyword != HtmlName::kPagespeedLscExpiry &&
        keyword != HtmlName::kPagespeedNoDefer &&
        keyword != HtmlName::kSrc) {
      GoogleString escaped_js;
      // Escape problematic characters but don't quote it as we do that.
      if (attr.DecodedValueOrNull() != NULL) {
        EscapeToJsStringLiteral(attr.DecodedValueOrNull(), false, &escaped_js);
      }
      StrAppend(&result, ", \"", attr.name_str(), "=", escaped_js, "\"");
    }
  }
  return result;
}

}  // namespace net_instaweb
<|endoftext|>


<commit_before><commit_msg>changes<commit_after><|endoftext|>