<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/extensions/permissions/api_permission.h"

#include "chrome/common/extensions/permissions/permissions_info.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace {

const char kOldUnlimitedStoragePermission[] = "unlimited_storage";
const char kWindowsPermission[] = "windows";
const char kTemporaryBackgroundAlias[] = "background_alias_do_not_use";

}  // namespace

namespace extensions {

//
// APIPermission
//

APIPermission::~APIPermission() {}

PermissionMessage APIPermission::GetMessage_() const {
  return PermissionMessage(
      message_id_, l10n_util::GetStringUTF16(l10n_message_id_));
}

APIPermission::APIPermission(
    ID id,
    const char* name,
    int l10n_message_id,
    PermissionMessage::ID message_id,
    int flags)
    : id_(id),
      name_(name),
      flags_(flags),
      l10n_message_id_(l10n_message_id),
      message_id_(message_id) {}

// static
void APIPermission::RegisterAllPermissions(
    PermissionsInfo* info) {

  struct PermissionRegistration {
    APIPermission::ID id;
    const char* name;
    int flags;
    int l10n_message_id;
    PermissionMessage::ID message_id;
  } PermissionsToRegister[] = {
    // Register permissions for all extension types.
    { kBackground, "background" },
    { kClipboardRead, "clipboardRead", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD,
      PermissionMessage::kClipboard },
    { kClipboardWrite, "clipboardWrite" },
    { kDeclarativeWebRequest, "declarativeWebRequest" },
    { kDownloads, "downloads", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS,
      PermissionMessage::kDownloads },
    { kExperimental, "experimental", kFlagCannotBeOptional },
    { kGeolocation, "geolocation", kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION,
      PermissionMessage::kGeolocation },
    { kNotification, "notifications" },
    { kUnlimitedStorage, "unlimitedStorage", kFlagCannotBeOptional },

    // Register hosted and packaged app permissions.
    { kAppNotifications, "appNotifications" },

    // Register extension permissions.
    { kActiveTab, "activeTab" },
    { kAlarms, "alarms" },
    { kBookmark, "bookmarks", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS,
      PermissionMessage::kBookmarks },
    { kBrowserTag, "browserTag", kFlagCannotBeOptional },
    { kBrowsingData, "browsingData" },
    { kCommands, "commands" },
    { kContentSettings, "contentSettings", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS,
      PermissionMessage::kContentSettings },
    { kContextMenus, "contextMenus" },
    { kCookie, "cookies" },
    { kFileBrowserHandler, "fileBrowserHandler", kFlagCannotBeOptional },
    { kFontSettings, "fontSettings", kFlagCannotBeOptional },
    { kHistory, "history", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,
      PermissionMessage::kBrowsingHistory },
    { kIdle, "idle" },
    { kInput, "input", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_INPUT,
      PermissionMessage::kInput },
    { kManagement, "management", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT,
      PermissionMessage::kManagement },
    { kMediaGalleries, "mediaGalleries" },
    { kMediaGalleriesRead, "mediaGalleriesRead" },
    { kPageCapture, "pageCapture", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_ALL_PAGES_CONTENT,
      PermissionMessage::kAllPageContent },
    { kPrivacy, "privacy", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_PRIVACY,
      PermissionMessage::kPrivacy },
    { kStorage, "storage" },
    { kTab, "tabs", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_TABS,
      PermissionMessage::kTabs },
    { kTopSites, "topSites", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,
      PermissionMessage::kBrowsingHistory },
    { kTts, "tts", 0, kFlagCannotBeOptional },
    { kTtsEngine, "ttsEngine", kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE,
      PermissionMessage::kTtsEngine },
    { kUsb, "usb", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_USB,
      PermissionMessage::kNone },
    { kWebNavigation, "webNavigation", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs },
    { kWebRequest, "webRequest" },
    { kWebRequestBlocking, "webRequestBlocking" },

    // Register private permissions.
    { kChromeosInfoPrivate, "chromeosInfoPrivate", kFlagCannotBeOptional },
    { kFileBrowserHandlerInternal, "fileBrowserHandlerInternal",
      kFlagCannotBeOptional },
    { kFileBrowserPrivate, "fileBrowserPrivate", kFlagCannotBeOptional },
    { kManagedModePrivate, "managedModePrivate", kFlagCannotBeOptional },
    { kMediaPlayerPrivate, "mediaPlayerPrivate", kFlagCannotBeOptional },
    { kMetricsPrivate, "metricsPrivate", kFlagCannotBeOptional },
    { kSystemPrivate, "systemPrivate", kFlagCannotBeOptional },
    { kChromeAuthPrivate, "chromeAuthPrivate", kFlagCannotBeOptional },
    { kInputMethodPrivate, "inputMethodPrivate", kFlagCannotBeOptional },
    { kEchoPrivate, "echoPrivate", kFlagCannotBeOptional },
    { kTerminalPrivate, "terminalPrivate", kFlagCannotBeOptional },
    { kWallpaperPrivate, "wallpaperPrivate", kFlagCannotBeOptional },
    { kWebRequestInternal, "webRequestInternal" },
    { kWebSocketProxyPrivate, "webSocketProxyPrivate", kFlagCannotBeOptional },
    { kWebstorePrivate, "webstorePrivate", kFlagCannotBeOptional },

    // Full url access permissions.
    { kProxy, "proxy", kFlagImpliesFullURLAccess | kFlagCannotBeOptional },
    { kDebugger, "debugger", kFlagImpliesFullURLAccess | kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_DEBUGGER,
      PermissionMessage::kDebugger },
    { kDevtools, "devtools",
      kFlagImpliesFullURLAccess | kFlagCannotBeOptional },
    { kPlugin, "plugin",
      kFlagImpliesFullURLAccess | kFlagImpliesFullAccess |
          kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS,
      PermissionMessage::kFullAccess },

    // Platform-app permissions.
    { kSocket, "socket", kFlagCannotBeOptional },
    { kAppWindow, "app.window" },
    { kAudioCapture, "audioCapture", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE,
      PermissionMessage::kAudioCapture },
    { kVideoCapture, "videoCapture", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE,
      PermissionMessage::kVideoCapture },
    { kFileSystem, "fileSystem" },
    { kFileSystemWrite, "fileSystemWrite", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE,
      PermissionMessage::kFileSystemWrite },
    { kMediaGalleriesAllGalleries, "mediaGalleriesAllGalleries",
      kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES,
      PermissionMessage::kMediaGalleriesAllGalleries },
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) {
    const PermissionRegistration& pr = PermissionsToRegister[i];
    info->RegisterPermission(
        pr.id, pr.name, pr.l10n_message_id,
        pr.message_id ? pr.message_id : PermissionMessage::kNone,
        pr.flags);
  }

  // Register aliases.
  info->RegisterAlias("unlimitedStorage", kOldUnlimitedStoragePermission);
  info->RegisterAlias("tabs", kWindowsPermission);
  // TODO(mihaip): Should be removed for the M20 branch, see
  // http://crbug.com/120447 for more details.
  info->RegisterAlias("background", kTemporaryBackgroundAlias);
}

}  // namespace extensions
<commit_msg>Explain why the 'fileSystem' permission has no permission string<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/extensions/permissions/api_permission.h"

#include "chrome/common/extensions/permissions/permissions_info.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace {

const char kOldUnlimitedStoragePermission[] = "unlimited_storage";
const char kWindowsPermission[] = "windows";
const char kTemporaryBackgroundAlias[] = "background_alias_do_not_use";

}  // namespace

namespace extensions {

//
// APIPermission
//

APIPermission::~APIPermission() {}

PermissionMessage APIPermission::GetMessage_() const {
  return PermissionMessage(
      message_id_, l10n_util::GetStringUTF16(l10n_message_id_));
}

APIPermission::APIPermission(
    ID id,
    const char* name,
    int l10n_message_id,
    PermissionMessage::ID message_id,
    int flags)
    : id_(id),
      name_(name),
      flags_(flags),
      l10n_message_id_(l10n_message_id),
      message_id_(message_id) {}

// static
void APIPermission::RegisterAllPermissions(
    PermissionsInfo* info) {

  struct PermissionRegistration {
    APIPermission::ID id;
    const char* name;
    int flags;
    int l10n_message_id;
    PermissionMessage::ID message_id;
  } PermissionsToRegister[] = {
    // Register permissions for all extension types.
    { kBackground, "background" },
    { kClipboardRead, "clipboardRead", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD,
      PermissionMessage::kClipboard },
    { kClipboardWrite, "clipboardWrite" },
    { kDeclarativeWebRequest, "declarativeWebRequest" },
    { kDownloads, "downloads", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS,
      PermissionMessage::kDownloads },
    { kExperimental, "experimental", kFlagCannotBeOptional },
    { kGeolocation, "geolocation", kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION,
      PermissionMessage::kGeolocation },
    { kNotification, "notifications" },
    { kUnlimitedStorage, "unlimitedStorage", kFlagCannotBeOptional },

    // Register hosted and packaged app permissions.
    { kAppNotifications, "appNotifications" },

    // Register extension permissions.
    { kActiveTab, "activeTab" },
    { kAlarms, "alarms" },
    { kBookmark, "bookmarks", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS,
      PermissionMessage::kBookmarks },
    { kBrowserTag, "browserTag", kFlagCannotBeOptional },
    { kBrowsingData, "browsingData" },
    { kCommands, "commands" },
    { kContentSettings, "contentSettings", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS,
      PermissionMessage::kContentSettings },
    { kContextMenus, "contextMenus" },
    { kCookie, "cookies" },
    { kFileBrowserHandler, "fileBrowserHandler", kFlagCannotBeOptional },
    { kFontSettings, "fontSettings", kFlagCannotBeOptional },
    { kHistory, "history", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,
      PermissionMessage::kBrowsingHistory },
    { kIdle, "idle" },
    { kInput, "input", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_INPUT,
      PermissionMessage::kInput },
    { kManagement, "management", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT,
      PermissionMessage::kManagement },
    { kMediaGalleries, "mediaGalleries" },
    { kMediaGalleriesRead, "mediaGalleriesRead" },
    { kPageCapture, "pageCapture", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_ALL_PAGES_CONTENT,
      PermissionMessage::kAllPageContent },
    { kPrivacy, "privacy", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_PRIVACY,
      PermissionMessage::kPrivacy },
    { kStorage, "storage" },
    { kTab, "tabs", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_TABS,
      PermissionMessage::kTabs },
    { kTopSites, "topSites", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,
      PermissionMessage::kBrowsingHistory },
    { kTts, "tts", 0, kFlagCannotBeOptional },
    { kTtsEngine, "ttsEngine", kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE,
      PermissionMessage::kTtsEngine },
    { kUsb, "usb", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_USB,
      PermissionMessage::kNone },
    { kWebNavigation, "webNavigation", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs },
    { kWebRequest, "webRequest" },
    { kWebRequestBlocking, "webRequestBlocking" },

    // Register private permissions.
    { kChromeosInfoPrivate, "chromeosInfoPrivate", kFlagCannotBeOptional },
    { kFileBrowserHandlerInternal, "fileBrowserHandlerInternal",
      kFlagCannotBeOptional },
    { kFileBrowserPrivate, "fileBrowserPrivate", kFlagCannotBeOptional },
    { kManagedModePrivate, "managedModePrivate", kFlagCannotBeOptional },
    { kMediaPlayerPrivate, "mediaPlayerPrivate", kFlagCannotBeOptional },
    { kMetricsPrivate, "metricsPrivate", kFlagCannotBeOptional },
    { kSystemPrivate, "systemPrivate", kFlagCannotBeOptional },
    { kChromeAuthPrivate, "chromeAuthPrivate", kFlagCannotBeOptional },
    { kInputMethodPrivate, "inputMethodPrivate", kFlagCannotBeOptional },
    { kEchoPrivate, "echoPrivate", kFlagCannotBeOptional },
    { kTerminalPrivate, "terminalPrivate", kFlagCannotBeOptional },
    { kWallpaperPrivate, "wallpaperPrivate", kFlagCannotBeOptional },
    { kWebRequestInternal, "webRequestInternal" },
    { kWebSocketProxyPrivate, "webSocketProxyPrivate", kFlagCannotBeOptional },
    { kWebstorePrivate, "webstorePrivate", kFlagCannotBeOptional },

    // Full url access permissions.
    { kProxy, "proxy", kFlagImpliesFullURLAccess | kFlagCannotBeOptional },
    { kDebugger, "debugger", kFlagImpliesFullURLAccess | kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_DEBUGGER,
      PermissionMessage::kDebugger },
    { kDevtools, "devtools",
      kFlagImpliesFullURLAccess | kFlagCannotBeOptional },
    { kPlugin, "plugin",
      kFlagImpliesFullURLAccess | kFlagImpliesFullAccess |
          kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS,
      PermissionMessage::kFullAccess },

    // Platform-app permissions.
    { kSocket, "socket", kFlagCannotBeOptional },
    { kAppWindow, "app.window" },
    { kAudioCapture, "audioCapture", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE,
      PermissionMessage::kAudioCapture },
    { kVideoCapture, "videoCapture", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE,
      PermissionMessage::kVideoCapture },
    // "fileSystem" has no permission string because read-only access is only
    // granted after the user has been shown a file chooser dialog and selected
    // a file. Selecting the file is considered consent to read it.
    { kFileSystem, "fileSystem" },
    { kFileSystemWrite, "fileSystemWrite", kFlagNone,
      IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE,
      PermissionMessage::kFileSystemWrite },
    { kMediaGalleriesAllGalleries, "mediaGalleriesAllGalleries",
      kFlagCannotBeOptional,
      IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES,
      PermissionMessage::kMediaGalleriesAllGalleries },
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) {
    const PermissionRegistration& pr = PermissionsToRegister[i];
    info->RegisterPermission(
        pr.id, pr.name, pr.l10n_message_id,
        pr.message_id ? pr.message_id : PermissionMessage::kNone,
        pr.flags);
  }

  // Register aliases.
  info->RegisterAlias("unlimitedStorage", kOldUnlimitedStoragePermission);
  info->RegisterAlias("tabs", kWindowsPermission);
  // TODO(mihaip): Should be removed for the M20 branch, see
  // http://crbug.com/120447 for more details.
  info->RegisterAlias("background", kTemporaryBackgroundAlias);
}

}  // namespace extensions
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pe_evalu.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 14:19:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/pe_evalu.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/idl/i_enumvalue.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary_i/codeinf2.hxx>
#include <s2_luidl/tk_ident.hxx>
#include <s2_luidl/tk_punct.hxx>
#include <s2_luidl/tk_const.hxx>

namespace csi
{
namespace uidl
{

#ifdef DF
#undef DF
#endif
#define DF  &PE_Value::On_Default

PE_Value::F_TOK
PE_Value::aDispatcher[PE_Value::e_STATES_MAX][PE_Value::tt_MAX] =
        {   { DF, DF, DF },  // e_none
            { &PE_Value::On_expect_name_Identifier,
                  DF, DF },  // expect_name
            { DF, &PE_Value::On_got_name_Punctuation,
                      &PE_Value::On_got_name_Assignment }  // got_name
        };

inline void
PE_Value::CallHandler( const char *     i_sTokenText,
                       E_TokenType      i_eTokenType )
    { (this->*aDispatcher[eState][i_eTokenType])(i_sTokenText); }

PE_Value::PE_Value( udmstri &   o_rName,
                    udmstri &   o_rAssignment,
                    bool        i_bIsConst )
    :   eState(e_none),
        pName(&o_rName),
        pAssignment(&o_rAssignment),
        bIsConst(i_bIsConst)
{
}

void
PE_Value::EstablishContacts( UnoIDL_PE *                io_pParentPE,
                             ary::n22::Repository &         io_rRepository,
                             TokenProcessing_Result &   o_rResult )
{
    UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);
}

PE_Value::~PE_Value()
{
}

void
PE_Value::ProcessToken( const Token & i_rToken )
{
    i_rToken.Trigger(*this);
}

void
PE_Value::Process_Identifier( const TokIdentifier & i_rToken )
{
    CallHandler(i_rToken.Text(), tt_identifier);
}

void
PE_Value::Process_Punctuation( const TokPunctuation & i_rToken )
{
    CallHandler(i_rToken.Text(), tt_punctuation);
}

void
PE_Value::Process_Assignment( const TokAssignment & i_rToken )
{
    CallHandler(i_rToken.Text(), tt_assignment);
}

void
PE_Value::On_expect_name_Identifier(const char * i_sText)
{
    *pName = i_sText;
    SetResult(done,stay);
    eState = got_name;
}

void
PE_Value::On_got_name_Punctuation(const char * i_sText)
{
    if ( i_sText[0] == ',' AND NOT IsConst()
         OR i_sText[0] == ';' AND IsConst() )
    {
        SetResult(done,pop_success);
        eState = e_none;
    }
    else if (i_sText[0] == '}' AND NOT IsConst())
    {
        SetResult(not_done,pop_success);
        eState = e_none;
    }
    else
        On_Default(i_sText);
}

void
PE_Value::On_got_name_Assignment(const char * i_sText)
{
    *pAssignment = i_sText;
    SetResult(done,pop_success);
    eState = e_none;
}

void
PE_Value::On_Default(const char * )
{
    SetResult(not_done,pop_failure);
}

void
PE_Value::InitData()
{
    eState = expect_name;

    *pName = "";
    *pAssignment = "";
}

void
PE_Value::TransferData()
{
    csv_assert(pName->length() > 0);
    eState = e_none;
}

UnoIDL_PE &
PE_Value::MyPE()
{
    return *this;
}

}   // namespace uidl
}   // namespace csi

<commit_msg>INTEGRATION: CWS adc18 (1.7.2); FILE MERGED 2007/10/19 10:37:31 np 1.7.2.2: #i81775# 2007/10/18 15:23:20 np 1.7.2.1: #i81775#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pe_evalu.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 17:06:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#include <precomp.h>
#include <s2_luidl/pe_evalu.hxx>

// NOT FULLY DECLARED SERVICES
#include <ary/idl/i_enumvalue.hxx>
#include <ary/idl/i_gate.hxx>
#include <ary/idl/ip_ce.hxx>
#include <ary/doc/d_oldidldocu.hxx>
#include <s2_luidl/tk_ident.hxx>
#include <s2_luidl/tk_punct.hxx>
#include <s2_luidl/tk_const.hxx>

namespace csi
{
namespace uidl
{

#ifdef DF
#undef DF
#endif
#define DF  &PE_Value::On_Default

PE_Value::F_TOK
PE_Value::aDispatcher[PE_Value::e_STATES_MAX][PE_Value::tt_MAX] =
        {   { DF, DF, DF },  // e_none
            { &PE_Value::On_expect_name_Identifier,
                  DF, DF },  // expect_name
            { DF, &PE_Value::On_got_name_Punctuation,
                      &PE_Value::On_got_name_Assignment }  // got_name
        };

inline void
PE_Value::CallHandler( const char *     i_sTokenText,
                       E_TokenType      i_eTokenType )
    { (this->*aDispatcher[eState][i_eTokenType])(i_sTokenText); }

PE_Value::PE_Value( String  &   o_rName,
                    String  &   o_rAssignment,
                    bool        i_bIsConst )
    :   eState(e_none),
        pName(&o_rName),
        pAssignment(&o_rAssignment),
        bIsConst(i_bIsConst)
{
}

void
PE_Value::EstablishContacts( UnoIDL_PE *                io_pParentPE,
                             ary::Repository &          io_rRepository,
                             TokenProcessing_Result &   o_rResult )
{
    UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);
}

PE_Value::~PE_Value()
{
}

void
PE_Value::ProcessToken( const Token & i_rToken )
{
    i_rToken.Trigger(*this);
}

void
PE_Value::Process_Identifier( const TokIdentifier & i_rToken )
{
    CallHandler(i_rToken.Text(), tt_identifier);
}

void
PE_Value::Process_Punctuation( const TokPunctuation & i_rToken )
{
    CallHandler(i_rToken.Text(), tt_punctuation);
}

void
PE_Value::Process_Assignment( const TokAssignment & i_rToken )
{
    CallHandler(i_rToken.Text(), tt_assignment);
}

void
PE_Value::On_expect_name_Identifier(const char * i_sText)
{
    *pName = i_sText;
    SetResult(done,stay);
    eState = got_name;
}

void
PE_Value::On_got_name_Punctuation(const char * i_sText)
{
    if ( i_sText[0] == ',' AND NOT IsConst()
         OR i_sText[0] == ';' AND IsConst() )
    {
        SetResult(done,pop_success);
        eState = e_none;
    }
    else if (i_sText[0] == '}' AND NOT IsConst())
    {
        SetResult(not_done,pop_success);
        eState = e_none;
    }
    else
        On_Default(i_sText);
}

void
PE_Value::On_got_name_Assignment(const char * i_sText)
{
    *pAssignment = i_sText;
    SetResult(done,pop_success);
    eState = e_none;
}

void
PE_Value::On_Default(const char * )
{
    SetResult(not_done,pop_failure);
}

void
PE_Value::InitData()
{
    eState = expect_name;

    *pName = "";
    *pAssignment = "";
}

void
PE_Value::TransferData()
{
    csv_assert(pName->length() > 0);
    eState = e_none;
}

UnoIDL_PE &
PE_Value::MyPE()
{
    return *this;
}

}   // namespace uidl
}   // namespace csi

<|endoftext|>


<commit_before><commit_msg>Task: Lexer::Type::word arguments are dequoted before being stored<commit_after><|endoftext|>


<commit_before>#line 2 "togo/utility/utility.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.

@file
@brief Utilities.
@ingroup utility
*/

#pragma once

#include <togo/config.hpp>
#include <togo/types.hpp>
#include <togo/error/assert.hpp>
#include <togo/utility/types.hpp>
#include <togo/utility/traits.hpp>
#include <togo/utility/constraints.hpp>

#include <type_traits>

namespace togo {

/**
	@addtogroup utility
	@{
*/

/** @name Type utilities */ /// @{

/// Cast unsigned integral to signed integral.
template<class T>
inline constexpr typename std::make_signed<T>::type
signed_cast(T const value) noexcept {
	return static_cast<typename std::make_signed<T>::type>(value);
}

/// Cast signed integral to unsigned integral.
template<class T>
inline constexpr typename std::make_unsigned<T>::type
unsigned_cast(T const value) noexcept {
	return static_cast<typename std::make_unsigned<T>::type>(value);
}

/// Get number of elements in bounded array.
template<class T, unsigned N>
inline constexpr unsigned
array_extent(T const (&)[N]) noexcept {
	return N;
}

/// Get number of elements in bounded array.
template<class T, class U, unsigned N>
inline constexpr unsigned
array_extent(T const (U::* const)[N]) noexcept {
	return N;
}

/// Get sizeof type or 0 if the type is empty.
template<class T>
inline constexpr unsigned
sizeof_empty() noexcept {
	return std::is_empty<T>::value ? 0 : sizeof(T);
}

/// @}

/** @name Misc utilities */ /// @{

/// Make an rvalue reference.
///
/// This is equivalent to std::move(), whose name is totally bonkers.
template<class T>
inline constexpr remove_ref<T>&& rvalue_ref(T&& x) noexcept {
	return static_cast<remove_ref<T>&&>(x);
}

/// Retain value category when passing to another function.
///
/// This is equivalent to std::forward().
template<class T>
inline constexpr T&& forward(remove_ref<T>& x) noexcept {
	return static_cast<T&&>(x);
}

template<class T>
inline constexpr T&& forward(remove_ref<T>&& x) noexcept {
	static_assert(
		!is_lvalue_reference<T>::value,
		"rvalue cannot be forwarded as an lvalue"
	);
	return static_cast<T&&>(x);
}

/// A type as an unevaluated value.
///
/// This is equivalent to std::declval().
template<class T>
inline add_rvalue_ref<T> type_value() noexcept;

/// Swap the values of two references.
template<class T>
inline void swap(T& x, T& y) {
	T temp = x;
	x = y;
	y = temp;
}

/// Less-than comparison operator wrapper.
template<class T>
inline bool less(T const& x, T const& y) {
	return x < y;
}

/// Greater-than comparison operator wrapper.
template<class T>
inline bool greater(T const& x, T const& y) {
	return x > y;
}

/// @}

/** @name Arithmetic utilities */ /// @{

/// Get the smallest of two values.
template<class T>
inline constexpr T min(T const x, T const y) noexcept {
	TOGO_CONSTRAIN_INTEGRAL(T);
	return x < y ? x : y;
}

/// Get the largest of two values.
template<class T>
inline constexpr T max(T const x, T const y) noexcept {
	TOGO_CONSTRAIN_INTEGRAL(T);
	return x > y ? x : y;
}

/// Clamp a value between a minimum and maximum.
template<class T>
inline constexpr T clamp(T const x, T const minimum, T const maximum) noexcept {
	TOGO_CONSTRAIN_INTEGRAL(T);
	return
		  x < minimum
		? minimum
		: x > maximum
		? maximum
		: x
	;
}

/// @}

/** @name Memory utilities */ /// @{

/// Advance pointer by bytes.
/// @warning This advances by bytes, not sizeof(T).
template<class T>
inline T* pointer_add(T* p, u32 const bytes) noexcept {
	return reinterpret_cast<T*>(
		reinterpret_cast<type_if<is_const<T>::value, char const*, char*>>(p) + bytes
	);
}

/// Aligns a pointer by moving it forward.
template<class T>
inline T* pointer_align(T* p, u32 const align) noexcept {
	u32 const m = reinterpret_cast<std::uintptr_t>(p) % align;
	if (m) {
		p = pointer_add(p, align - m);
	}
	return p;
}

/// @}

/** @name Enum utilities */ /// @{

/// Return true whether an enum value is non-zero.
template<class T>
inline constexpr bool enum_bool(T const value) {
	static_assert(
		std::is_enum<T>::value,
		"T must be an enum"
	);
	return static_cast<typename std::underlying_type<T>::type>(value);
}

/** @cond INTERNAL */
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator|(FlagT const& x, FlagT const& y) noexcept {
	return static_cast<FlagT>(
		static_cast<unsigned>(x) | static_cast<unsigned>(y)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator&(FlagT const& x, FlagT const& y) noexcept {
	return static_cast<FlagT>(
		static_cast<unsigned>(x) & static_cast<unsigned>(y)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator~(FlagT const& x) noexcept {
	return static_cast<FlagT>(
		~static_cast<unsigned>(x)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator|=(FlagT& x, FlagT const& y) noexcept {
	return x = static_cast<FlagT>(
		static_cast<unsigned>(x) | static_cast<unsigned>(y)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator&=(FlagT& x, FlagT const& y) noexcept {
	return x = static_cast<FlagT>(
		static_cast<unsigned>(x) & static_cast<unsigned>(y)
	);
}
/** @endcond */ // INTERNAL

/// @}

/** @name Collection utilities */ /// @{

template<class T>
struct ArrayRef {
	T* _begin;
	T* _end;

	inline ArrayRef(T* const begin, T* const end)
		: _begin(begin)
		, _end(end)
	{}

	template<class U, class = enable_if<std::is_convertible<U, T>::value>>
	inline ArrayRef(ArrayRef<U> const& other)
		: _begin(other._begin)
		, _end(other._end)
	{}

	/// Number of items.
	unsigned size() const {
		return _end - _begin;
	}

	/// Access value by index.
	T& operator[](unsigned const i) {
		TOGO_DEBUG_ASSERTE(_begin + i < _end);
		return _begin[i];
	}

	/// Access value by index.
	T const& operator[](unsigned const i) const {
		TOGO_DEBUG_ASSERTE(_begin + i < _end);
		return _begin[i];
	}
};

/// Make reference to array.
template<class T>
inline ArrayRef<T> array_ref(unsigned const size, T* const data) {
	return ArrayRef<T>{data, data + size};
}

/** @cond INTERNAL */
template<class T>
inline T* begin(ArrayRef<T> const& ar) { return ar._begin; }

template<class T>
inline T const* cbegin(ArrayRef<T> const& ar) { return ar._begin; }

template<class T>
inline T* end(ArrayRef<T> const& ar) { return ar._end; }

template<class T>
inline T const* cend(ArrayRef<T> const& ar) { return ar._end; }
/** @endcond */ // INTERNAL

/// @}

/** @} */ // end of doc-group utility

} // namespace togo
<commit_msg>utility: added null_ref_tag ArrayRef<T> ctor.<commit_after>#line 2 "togo/utility/utility.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.

@file
@brief Utilities.
@ingroup utility
*/

#pragma once

#include <togo/config.hpp>
#include <togo/types.hpp>
#include <togo/error/assert.hpp>
#include <togo/utility/types.hpp>
#include <togo/utility/tags.hpp>
#include <togo/utility/traits.hpp>
#include <togo/utility/constraints.hpp>

#include <type_traits>

namespace togo {

/**
	@addtogroup utility
	@{
*/

/** @name Type utilities */ /// @{

/// Cast unsigned integral to signed integral.
template<class T>
inline constexpr typename std::make_signed<T>::type
signed_cast(T const value) noexcept {
	return static_cast<typename std::make_signed<T>::type>(value);
}

/// Cast signed integral to unsigned integral.
template<class T>
inline constexpr typename std::make_unsigned<T>::type
unsigned_cast(T const value) noexcept {
	return static_cast<typename std::make_unsigned<T>::type>(value);
}

/// Get number of elements in bounded array.
template<class T, unsigned N>
inline constexpr unsigned
array_extent(T const (&)[N]) noexcept {
	return N;
}

/// Get number of elements in bounded array.
template<class T, class U, unsigned N>
inline constexpr unsigned
array_extent(T const (U::* const)[N]) noexcept {
	return N;
}

/// Get sizeof type or 0 if the type is empty.
template<class T>
inline constexpr unsigned
sizeof_empty() noexcept {
	return std::is_empty<T>::value ? 0 : sizeof(T);
}

/// @}

/** @name Misc utilities */ /// @{

/// Make an rvalue reference.
///
/// This is equivalent to std::move(), whose name is totally bonkers.
template<class T>
inline constexpr remove_ref<T>&& rvalue_ref(T&& x) noexcept {
	return static_cast<remove_ref<T>&&>(x);
}

/// Retain value category when passing to another function.
///
/// This is equivalent to std::forward().
template<class T>
inline constexpr T&& forward(remove_ref<T>& x) noexcept {
	return static_cast<T&&>(x);
}

template<class T>
inline constexpr T&& forward(remove_ref<T>&& x) noexcept {
	static_assert(
		!is_lvalue_reference<T>::value,
		"rvalue cannot be forwarded as an lvalue"
	);
	return static_cast<T&&>(x);
}

/// A type as an unevaluated value.
///
/// This is equivalent to std::declval().
template<class T>
inline add_rvalue_ref<T> type_value() noexcept;

/// Swap the values of two references.
template<class T>
inline void swap(T& x, T& y) {
	T temp = x;
	x = y;
	y = temp;
}

/// Less-than comparison operator wrapper.
template<class T>
inline bool less(T const& x, T const& y) {
	return x < y;
}

/// Greater-than comparison operator wrapper.
template<class T>
inline bool greater(T const& x, T const& y) {
	return x > y;
}

/// @}

/** @name Arithmetic utilities */ /// @{

/// Get the smallest of two values.
template<class T>
inline constexpr T min(T const x, T const y) noexcept {
	TOGO_CONSTRAIN_INTEGRAL(T);
	return x < y ? x : y;
}

/// Get the largest of two values.
template<class T>
inline constexpr T max(T const x, T const y) noexcept {
	TOGO_CONSTRAIN_INTEGRAL(T);
	return x > y ? x : y;
}

/// Clamp a value between a minimum and maximum.
template<class T>
inline constexpr T clamp(T const x, T const minimum, T const maximum) noexcept {
	TOGO_CONSTRAIN_INTEGRAL(T);
	return
		  x < minimum
		? minimum
		: x > maximum
		? maximum
		: x
	;
}

/// @}

/** @name Memory utilities */ /// @{

/// Advance pointer by bytes.
/// @warning This advances by bytes, not sizeof(T).
template<class T>
inline T* pointer_add(T* p, u32 const bytes) noexcept {
	return reinterpret_cast<T*>(
		reinterpret_cast<type_if<is_const<T>::value, char const*, char*>>(p) + bytes
	);
}

/// Aligns a pointer by moving it forward.
template<class T>
inline T* pointer_align(T* p, u32 const align) noexcept {
	u32 const m = reinterpret_cast<std::uintptr_t>(p) % align;
	if (m) {
		p = pointer_add(p, align - m);
	}
	return p;
}

/// @}

/** @name Enum utilities */ /// @{

/// Return true whether an enum value is non-zero.
template<class T>
inline constexpr bool enum_bool(T const value) {
	static_assert(
		std::is_enum<T>::value,
		"T must be an enum"
	);
	return static_cast<typename std::underlying_type<T>::type>(value);
}

/** @cond INTERNAL */
template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator|(FlagT const& x, FlagT const& y) noexcept {
	return static_cast<FlagT>(
		static_cast<unsigned>(x) | static_cast<unsigned>(y)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator&(FlagT const& x, FlagT const& y) noexcept {
	return static_cast<FlagT>(
		static_cast<unsigned>(x) & static_cast<unsigned>(y)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT operator~(FlagT const& x) noexcept {
	return static_cast<FlagT>(
		~static_cast<unsigned>(x)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator|=(FlagT& x, FlagT const& y) noexcept {
	return x = static_cast<FlagT>(
		static_cast<unsigned>(x) | static_cast<unsigned>(y)
	);
}

template<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>
inline constexpr FlagT& operator&=(FlagT& x, FlagT const& y) noexcept {
	return x = static_cast<FlagT>(
		static_cast<unsigned>(x) & static_cast<unsigned>(y)
	);
}
/** @endcond */ // INTERNAL

/// @}

/** @name Collection utilities */ /// @{

template<class T>
struct ArrayRef {
	T* _begin;
	T* _end;

	inline ArrayRef(null_ref_tag const)
		: _begin(nullptr)
		, _end(nullptr)
	{}

	inline ArrayRef(T* const begin, T* const end)
		: _begin(begin)
		, _end(end)
	{}

	template<class U, class = enable_if<std::is_convertible<U, T>::value>>
	inline ArrayRef(ArrayRef<U> const& other)
		: _begin(other._begin)
		, _end(other._end)
	{}

	/// Number of items.
	unsigned size() const {
		return _end - _begin;
	}

	/// Access value by index.
	T& operator[](unsigned const i) {
		TOGO_DEBUG_ASSERTE(_begin + i < _end);
		return _begin[i];
	}

	/// Access value by index.
	T const& operator[](unsigned const i) const {
		TOGO_DEBUG_ASSERTE(_begin + i < _end);
		return _begin[i];
	}
};

/// Make reference to array.
template<class T>
inline ArrayRef<T> array_ref(unsigned const size, T* const data) {
	return ArrayRef<T>{data, data + size};
}

/** @cond INTERNAL */
template<class T>
inline T* begin(ArrayRef<T> const& ar) { return ar._begin; }

template<class T>
inline T const* cbegin(ArrayRef<T> const& ar) { return ar._begin; }

template<class T>
inline T* end(ArrayRef<T> const& ar) { return ar._end; }

template<class T>
inline T const* cend(ArrayRef<T> const& ar) { return ar._end; }
/** @endcond */ // INTERNAL

/// @}

/** @} */ // end of doc-group utility

} // namespace togo
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver.
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QtPlugin>
#include <QDebug>
#include <QHash>

#include <QVariant>

//#include <QDomElement>
//#include <QDomDocument>

#include <visualizeraccessor.h>
#include <tasqtdatamodel.h>

#include <tdriver_tabbededitor.h>
//
//#include <dispatcher.h>
//#include <includes.h>

Q_EXPORT_PLUGIN2(visualizeraccessor, VisualizerAccessor)

// fixture version information
static QString FIXTURE_NAME = "VisualizerAccessor";
static QString FIXTURE_VERSION = "0.1";
static QString FIXTURE_DESCRIPTION = "API for accessing applications internal Qt methods";

// hash keys
static QString CLASS_NAME = "class";
static QString METHOD_NAME = "method";
static QString METHOD_ARGS = "args";

// Constructor
VisualizerAccessor::VisualizerAccessor( QObject *parent ) : QObject( parent )
{

}

bool VisualizerAccessor::execute(void * objectInstance, QString commandName, QHash<QString, QString> parameters, QString & resultString)
{
    qDebug() << "VisualizerAccessor::execute";
    qDebug() << "command:" << commandName;
    qDebug() << "parameters" << parameters;

    bool result = false;
    resultString = commandName;

    static QStringList valid_commands(QStringList() << "ping" << "editor_save" << "editor_load");

    if (!valid_commands.contains(commandName)) {
        resultString += " error: invalid command";
    }

    // first commands that do not need editor instance
    else if (commandName == "ping") {
        if (parameters.contains("data")) resultString = parameters["data"];
        else resultString = "pong";
        result = true;
    }

    // then commands that need editor instance
    else {
        // TODO: add code to check that objectInstance really is a QObject pointer
        TDriverTabbedEditor *tabs = qobject_cast<TDriverTabbedEditor*>(
                    reinterpret_cast<QObject*>(objectInstance));
        QString className = (tabs) ? tabs->metaObject()->className() : "<invalid>";

        if (!tabs) {
            resultString = (commandName + " error: invalid object @0x%1 class name '%2'")
                    .arg(reinterpret_cast<uint>(objectInstance), 8, 16, QChar('0'))
                    .arg(className);
        }

        else if (commandName == "editor_save") {
            if (parameters.contains("filename")) {
                int index = QVariant(parameters.value("tabindex", "-1")).toInt(&result);
                if (result) {
                    result = tabs->saveFile(parameters["filename"], index, true);
                    resultString += ": saveFile called";
                }
                else {
                    resultString += " error: invalid tab index";
                }
            }
            else {
                resultString += " error: missing command parameter: filename";
            }
        }

        else if (commandName == "editor_load") {
            if (parameters.contains("filename")) {
                result = tabs->loadFile(parameters["filename"], QVariant(parameters.value("istemplate", false)).toBool());
                resultString += ": loadFile called";
            }
            else
                resultString += " error: missing command parameter: filename";
        }
    }

    return result;

}
<commit_msg>Fixed one more 64 bit incompatible cast from pointer to integer, in fixture.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver.
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QtPlugin>
#include <QDebug>
#include <QHash>

#include <QVariant>

//#include <QDomElement>
//#include <QDomDocument>

#include <visualizeraccessor.h>
#include <tasqtdatamodel.h>

#include <tdriver_tabbededitor.h>
//
//#include <dispatcher.h>
//#include <includes.h>

Q_EXPORT_PLUGIN2(visualizeraccessor, VisualizerAccessor)

// fixture version information
static QString FIXTURE_NAME = "VisualizerAccessor";
static QString FIXTURE_VERSION = "0.1";
static QString FIXTURE_DESCRIPTION = "API for accessing applications internal Qt methods";

// hash keys
static QString CLASS_NAME = "class";
static QString METHOD_NAME = "method";
static QString METHOD_ARGS = "args";

// Constructor
VisualizerAccessor::VisualizerAccessor( QObject *parent ) : QObject( parent )
{

}

bool VisualizerAccessor::execute(void * objectInstance, QString commandName, QHash<QString, QString> parameters, QString & resultString)
{
    qDebug() << "VisualizerAccessor::execute";
    qDebug() << "command:" << commandName;
    qDebug() << "parameters" << parameters;

    bool result = false;
    resultString = commandName;

    static QStringList valid_commands(QStringList() << "ping" << "editor_save" << "editor_load");

    if (!valid_commands.contains(commandName)) {
        resultString += " error: invalid command";
    }

    // first commands that do not need editor instance
    else if (commandName == "ping") {
        if (parameters.contains("data")) resultString = parameters["data"];
        else resultString = "pong";
        result = true;
    }

    // then commands that need editor instance
    else {
        // TODO: add code to check that objectInstance really is a QObject pointer
        TDriverTabbedEditor *tabs = qobject_cast<TDriverTabbedEditor*>(
                    reinterpret_cast<QObject*>(objectInstance));
        QString className = (tabs) ? tabs->metaObject()->className() : "<invalid>";

        if (!tabs) {
            resultString = (commandName + " error: invalid object @0x%1 class name '%2'")
                    .arg(reinterpret_cast<ulong>(objectInstance), 8, 16, QChar('0'))
                    .arg(className);
        }

        else if (commandName == "editor_save") {
            if (parameters.contains("filename")) {
                int index = QVariant(parameters.value("tabindex", "-1")).toInt(&result);
                if (result) {
                    result = tabs->saveFile(parameters["filename"], index, true);
                    resultString += ": saveFile called";
                }
                else {
                    resultString += " error: invalid tab index";
                }
            }
            else {
                resultString += " error: missing command parameter: filename";
            }
        }

        else if (commandName == "editor_load") {
            if (parameters.contains("filename")) {
                result = tabs->loadFile(parameters["filename"], QVariant(parameters.value("istemplate", false)).toBool());
                resultString += ": loadFile called";
            }
            else
                resultString += " error: missing command parameter: filename";
        }
    }

    return result;

}
<|endoftext|>


<commit_before>
#include "Gameboy.hpp"

#include "OpenGLWindow.hpp"
#include "DbWindow.hpp"
#include "registerAddr.hpp"

#include "Cpu.hpp"
#include "Gpu.hpp"
#include "Memory.hpp"
#include "Timer.hpp"
#include "Audio.hpp"

void setLowBit(Memory *memory, uint16_t addr, uint8_t bit)
{
	memory->write_byte(addr, (uint8_t)((0x01 << bit) ^ memory->read_byte(addr)), true);
}

void setHightBit(Memory *memory, uint16_t addr, uint8_t bit)
{
	memory->write_byte(addr, (uint8_t)((0x01 << bit) | memory->read_byte(addr)), true);
}

Gameboy::Gameboy(const char *path) :
	_window(OpenGLWindow::Instance())
	, _windowDebug(nullptr)
	, _thread(nullptr)
	, _romPath(path)
{
	_stepMode.store(false);
	_willRun.store(false);

	connect(_window, &OpenGLWindow::openRomSign, this, &Gameboy::openRomSlot);
	connect(_window, &OpenGLWindow::gbDbSign, this, &Gameboy::gbDbSlot);
	connect(_window, &OpenGLWindow::keyPressSign, this, &Gameboy::KeyPress);
	connect(_window, &OpenGLWindow::keyReleaseSign, this, &Gameboy::KeyRelease);
	connect(_window, &OpenGLWindow::gbTypeSign, this, &Gameboy::gbTypeSlot);
	connect(_window, &OpenGLWindow::gbComPlay, this, &Gameboy::switchPlaySlot);
	connect(_window, &OpenGLWindow::gbComPause, this, &Gameboy::switchPauseSlot);
	connect(_window, &OpenGLWindow::gbComStop, this, &Gameboy::resetPressedSlot);
	connect(_window, &OpenGLWindow::gbSoundSign, this, &Gameboy::soundSlot);

	_window->show();
#ifdef DEBUG
	gbDbSlot(); // Open Debug window
	reset();
#endif
}

Gameboy::~Gameboy()
{
	this->_memory->saverom();
	delete this->_windowDebug;
	this->stopThread();
}

void	Gameboy::stopThread()
{
	_stepMode.store(true);
	_willRun.store(false);
	if (_thread)
	{
		_thread->join();
		delete _thread;
		_thread = nullptr;
	}
}

void	Gameboy::gstep()
{
	step();
	if (isBreakpoint(_cpu->_cpuRegister.PC))
		_stepMode.store(true);
}

void	Gameboy::run()
{
	while (_willRun.load())
	{
		if (!_stepMode.load())
		{
			gstep();
		}
	}
}

void	Gameboy::reset(void)
{
	if (_willRun.load())
	{
		stopThread();
	}

	if (_romPath.length())
	{
		this->_memory->reset();
		this->_memory->setAudio(_audio);
		this->_clock->reset();
		this->_audio->reset(_memory->getRomType() == GBC);
		this->_cyclesAcc = 0;
		if (_memory->loadRom(_romPath.c_str(), this->_hardware) == 0)
		{
			htype		hardRom;
			hardRom = (this->_hardware == AUTO) ? this->_memory->getRomType() : this->_hardware;
			this->_cpu->init(hardRom);
			this->_gpu->init(); // TODO pour passer hardware au gpu: this->_gpu->init(hardRom)
			_willRun.store(true);
			_thread = new std::thread(&Gameboy::run, this);
		}
	}
	else
		std::cerr << "Gameboy: No rom path defined" << std::endl;
}

void	Gameboy::gbTypeSlot(htype hardware)
{
	this->_hardware = hardware;
}

void	Gameboy::stepPressedSlot(unsigned int count)
{
	_stepMode.store(true);
	while (count--) {
		gstep();
		if (isBreakpoint(_cpu->_cpuRegister.PC))
			break ;
	}
}

#include "registerAddr.hpp"
void	Gameboy::framePressedSlot()
{
	_stepMode.store(true);
	bool			cte = true;

	uint16_t	start;
	start = _memory->read_byte(REGISTER_LY);
	while (start == _memory->read_byte(REGISTER_LY) && cte) {
		gstep();
		cte = !isBreakpoint(_cpu->_cpuRegister.PC);
	}
	while (start != _memory->read_byte(REGISTER_LY) && cte) {
		gstep();
		cte = !isBreakpoint(_cpu->_cpuRegister.PC);
	}
}

void	Gameboy::resetPressedSlot()
{
	_stepMode.store(true);
	reset();
}

void	Gameboy::openRomSlot(std::string path)
{
	_romPath = path;
	reset();
	_stepMode.store(false);
}

void	Gameboy::gbDbSlot()
{
	_windowDebug = new DbWindow(&_cpu->_cpuRegister, _memory, &_breakpoints);
	connect(_windowDebug, &DbWindow::stepPressedSign, this, &Gameboy::stepPressedSlot);
	connect(_windowDebug, &DbWindow::framePressedSign, this, &Gameboy::framePressedSlot);
	connect(_windowDebug, &DbWindow::runPressedSign, this, &Gameboy::switchStepModeSlot);
	connect(_windowDebug, &DbWindow::resetPressedSign, this, &Gameboy::resetPressedSlot);
	connect(_windowDebug, &DbWindow::openPressedSign, this, &Gameboy::openRomSlot);

	connect(_windowDebug, &DbWindow::bpAddSign, this, &Gameboy::addBreakpointSlot);
	connect(_windowDebug, &DbWindow::bpDelSign, this, &Gameboy::delBreakpointSlot);

	_windowDebug->show();
	_stepMode.store(true);
}

void	Gameboy::switchPlaySlot(void)
{
	_stepMode.store(false);
}

void	Gameboy::switchPauseSlot(void)
{
	_stepMode.store(true);
}

void	Gameboy::soundSlot(bool on)
{
	_audio->enable(on);
}

void	Gameboy::switchStepModeSlot(void)
{
	_stepMode.store(!_stepMode.load());
}

void	Gameboy::addBreakpointSlot(uint16_t addr)
{
	auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);

	if (it == _breakpoints.end())
		_breakpoints.push_back(addr);
}

void	Gameboy::delBreakpointSlot(uint16_t addr)
{
	_breakpoints.remove(addr);
}

bool	Gameboy::isBreakpoint(uint16_t addr)
{
	auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);

	return (it != _breakpoints.end());
}

void	Gameboy::KeyPress(int key)
{
	switch(key)
	{
		case RIGHT:
			_memory->key[0] &= 0x0e;
			setLowBit(_memory, REGISTER_INPUT, 0);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case A_BUTTON:
			_memory->key[1] &= 0x0e;
			setLowBit(_memory, REGISTER_INPUT, 0);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case LEFT:
			_memory->key[0] &= 0x0D;
			setLowBit(_memory, REGISTER_INPUT, 1);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case B_BUTTON:
			_memory->key[1] &= 0x0D;
			setLowBit(_memory, REGISTER_INPUT, 1);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case UP:
			_memory->key[0] &= 0x0B;
			setLowBit(_memory, REGISTER_INPUT, 2);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case SELECT:
			_memory->key[1] &= 0x0B;
			setLowBit(_memory, REGISTER_INPUT, 2);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case DOWN:
			_memory->key[0] &= 0x07;
			setLowBit(_memory, REGISTER_INPUT, 3);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case START:
			_memory->key[1] &= 0x07;
			setLowBit(_memory, REGISTER_INPUT, 3);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
	}
}

void	Gameboy::KeyRelease(int key)
{
	switch(key)
	{
		case RIGHT:
			_memory->key[0] |= 0x01;
			setHightBit(_memory, REGISTER_INPUT, 0);
			_cpu->setStop(false);
			break;
		case A_BUTTON:
			_memory->key[1] |= 0x01;
			setHightBit(_memory, REGISTER_INPUT, 0);
			_cpu->setStop(false);
			break;
		case LEFT:
			_memory->key[0] |= 0x02;
			setHightBit(_memory, REGISTER_INPUT, 1);
			_cpu->setStop(false);
			break;
		case B_BUTTON:
			_memory->key[1] |= 0x02;
			setHightBit(_memory, REGISTER_INPUT, 1);
			_cpu->setStop(false);
			break;
		case UP:
			_memory->key[0] |= 0x04;
			setHightBit(_memory, REGISTER_INPUT, 2);
			_cpu->setStop(false);
			break;
		case SELECT:
			_memory->key[1] |= 0x04;
			setHightBit(_memory, REGISTER_INPUT, 2);
			_cpu->setStop(false);
			break;
		case DOWN:
			_memory->key[0] |= 0x08;
			setHightBit(_memory, REGISTER_INPUT, 3);
			_cpu->setStop(false);
			break;
		case START:
			_memory->key[1] |= 0x08;
			setHightBit(_memory, REGISTER_INPUT, 3);
			_cpu->setStop(false);
			break;
	}
}

<commit_msg>Ajout message WARNING segment fault<commit_after>
#include "Gameboy.hpp"

#include "OpenGLWindow.hpp"
#include "DbWindow.hpp"
#include "registerAddr.hpp"

#include "Cpu.hpp"
#include "Gpu.hpp"
#include "Memory.hpp"
#include "Timer.hpp"
#include "Audio.hpp"

void setLowBit(Memory *memory, uint16_t addr, uint8_t bit)
{
	memory->write_byte(addr, (uint8_t)((0x01 << bit) ^ memory->read_byte(addr)), true);
}

void setHightBit(Memory *memory, uint16_t addr, uint8_t bit)
{
	memory->write_byte(addr, (uint8_t)((0x01 << bit) | memory->read_byte(addr)), true);
}

Gameboy::Gameboy(const char *path) :
	_window(OpenGLWindow::Instance())
	, _windowDebug(nullptr)
	, _thread(nullptr)
	, _romPath(path)
{
	_stepMode.store(false);
	_willRun.store(false);

	connect(_window, &OpenGLWindow::openRomSign, this, &Gameboy::openRomSlot);
	connect(_window, &OpenGLWindow::gbDbSign, this, &Gameboy::gbDbSlot);
	connect(_window, &OpenGLWindow::keyPressSign, this, &Gameboy::KeyPress);
	connect(_window, &OpenGLWindow::keyReleaseSign, this, &Gameboy::KeyRelease);
	connect(_window, &OpenGLWindow::gbTypeSign, this, &Gameboy::gbTypeSlot);
	connect(_window, &OpenGLWindow::gbComPlay, this, &Gameboy::switchPlaySlot);
	connect(_window, &OpenGLWindow::gbComPause, this, &Gameboy::switchPauseSlot);
	connect(_window, &OpenGLWindow::gbComStop, this, &Gameboy::resetPressedSlot);
	connect(_window, &OpenGLWindow::gbSoundSign, this, &Gameboy::soundSlot);

	_window->show();
#ifdef DEBUG
	gbDbSlot(); // Open Debug window. WARNING: Peux generer SGFAULT random
	reset();
#endif
}

Gameboy::~Gameboy()
{
	this->_memory->saverom();
	delete this->_windowDebug;
	this->stopThread();
}

void	Gameboy::stopThread()
{
	_stepMode.store(true);
	_willRun.store(false);
	if (_thread)
	{
		_thread->join();
		delete _thread;
		_thread = nullptr;
	}
}

void	Gameboy::gstep()
{
	step();
	if (isBreakpoint(_cpu->_cpuRegister.PC))
		_stepMode.store(true);
}

void	Gameboy::run()
{
	while (_willRun.load())
	{
		if (!_stepMode.load())
		{
			gstep();
		}
	}
}

void	Gameboy::reset(void)
{
	if (_willRun.load())
	{
		stopThread();
	}

	if (_romPath.length())
	{
		this->_memory->reset();
		this->_memory->setAudio(_audio);
		this->_clock->reset();
		this->_audio->reset(_memory->getRomType() == GBC);
		this->_cyclesAcc = 0;
		if (_memory->loadRom(_romPath.c_str(), this->_hardware) == 0)
		{
			htype		hardRom;
			hardRom = (this->_hardware == AUTO) ? this->_memory->getRomType() : this->_hardware;
			this->_cpu->init(hardRom);
			this->_gpu->init(); // TODO pour passer hardware au gpu: this->_gpu->init(hardRom)
			_willRun.store(true);
			_thread = new std::thread(&Gameboy::run, this);
		}
	}
	else
		std::cerr << "Gameboy: No rom path defined" << std::endl;
}

void	Gameboy::gbTypeSlot(htype hardware)
{
	this->_hardware = hardware;
}

void	Gameboy::stepPressedSlot(unsigned int count)
{
	_stepMode.store(true);
	while (count--) {
		gstep();
		if (isBreakpoint(_cpu->_cpuRegister.PC))
			break ;
	}
}

#include "registerAddr.hpp"
void	Gameboy::framePressedSlot()
{
	_stepMode.store(true);
	bool			cte = true;

	uint16_t	start;
	start = _memory->read_byte(REGISTER_LY);
	while (start == _memory->read_byte(REGISTER_LY) && cte) {
		gstep();
		cte = !isBreakpoint(_cpu->_cpuRegister.PC);
	}
	while (start != _memory->read_byte(REGISTER_LY) && cte) {
		gstep();
		cte = !isBreakpoint(_cpu->_cpuRegister.PC);
	}
}

void	Gameboy::resetPressedSlot()
{
	_stepMode.store(true);
	reset();
}

void	Gameboy::openRomSlot(std::string path)
{
	_romPath = path;
	reset();
	_stepMode.store(false);
}

void	Gameboy::gbDbSlot()
{
	_windowDebug = new DbWindow(&_cpu->_cpuRegister, _memory, &_breakpoints);
	connect(_windowDebug, &DbWindow::stepPressedSign, this, &Gameboy::stepPressedSlot);
	connect(_windowDebug, &DbWindow::framePressedSign, this, &Gameboy::framePressedSlot);
	connect(_windowDebug, &DbWindow::runPressedSign, this, &Gameboy::switchStepModeSlot);
	connect(_windowDebug, &DbWindow::resetPressedSign, this, &Gameboy::resetPressedSlot);
	connect(_windowDebug, &DbWindow::openPressedSign, this, &Gameboy::openRomSlot);

	connect(_windowDebug, &DbWindow::bpAddSign, this, &Gameboy::addBreakpointSlot);
	connect(_windowDebug, &DbWindow::bpDelSign, this, &Gameboy::delBreakpointSlot);

	_windowDebug->show();
	_stepMode.store(true);
}

void	Gameboy::switchPlaySlot(void)
{
	_stepMode.store(false);
}

void	Gameboy::switchPauseSlot(void)
{
	_stepMode.store(true);
}

void	Gameboy::soundSlot(bool on)
{
	_audio->enable(on);
}

void	Gameboy::switchStepModeSlot(void)
{
	_stepMode.store(!_stepMode.load());
}

void	Gameboy::addBreakpointSlot(uint16_t addr)
{
	auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);

	if (it == _breakpoints.end())
		_breakpoints.push_back(addr);
}

void	Gameboy::delBreakpointSlot(uint16_t addr)
{
	_breakpoints.remove(addr);
}

bool	Gameboy::isBreakpoint(uint16_t addr)
{
	auto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);

	return (it != _breakpoints.end());
}

void	Gameboy::KeyPress(int key)
{
	switch(key)
	{
		case RIGHT:
			_memory->key[0] &= 0x0e;
			setLowBit(_memory, REGISTER_INPUT, 0);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case A_BUTTON:
			_memory->key[1] &= 0x0e;
			setLowBit(_memory, REGISTER_INPUT, 0);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case LEFT:
			_memory->key[0] &= 0x0D;
			setLowBit(_memory, REGISTER_INPUT, 1);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case B_BUTTON:
			_memory->key[1] &= 0x0D;
			setLowBit(_memory, REGISTER_INPUT, 1);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case UP:
			_memory->key[0] &= 0x0B;
			setLowBit(_memory, REGISTER_INPUT, 2);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case SELECT:
			_memory->key[1] &= 0x0B;
			setLowBit(_memory, REGISTER_INPUT, 2);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case DOWN:
			_memory->key[0] &= 0x07;
			setLowBit(_memory, REGISTER_INPUT, 3);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
		case START:
			_memory->key[1] &= 0x07;
			setLowBit(_memory, REGISTER_INPUT, 3);
			setHightBit(_memory, REGISTER_IF, 4);
			_cpu->setStop(false);
			break;
	}
}

void	Gameboy::KeyRelease(int key)
{
	switch(key)
	{
		case RIGHT:
			_memory->key[0] |= 0x01;
			setHightBit(_memory, REGISTER_INPUT, 0);
			_cpu->setStop(false);
			break;
		case A_BUTTON:
			_memory->key[1] |= 0x01;
			setHightBit(_memory, REGISTER_INPUT, 0);
			_cpu->setStop(false);
			break;
		case LEFT:
			_memory->key[0] |= 0x02;
			setHightBit(_memory, REGISTER_INPUT, 1);
			_cpu->setStop(false);
			break;
		case B_BUTTON:
			_memory->key[1] |= 0x02;
			setHightBit(_memory, REGISTER_INPUT, 1);
			_cpu->setStop(false);
			break;
		case UP:
			_memory->key[0] |= 0x04;
			setHightBit(_memory, REGISTER_INPUT, 2);
			_cpu->setStop(false);
			break;
		case SELECT:
			_memory->key[1] |= 0x04;
			setHightBit(_memory, REGISTER_INPUT, 2);
			_cpu->setStop(false);
			break;
		case DOWN:
			_memory->key[0] |= 0x08;
			setHightBit(_memory, REGISTER_INPUT, 3);
			_cpu->setStop(false);
			break;
		case START:
			_memory->key[1] |= 0x08;
			setHightBit(_memory, REGISTER_INPUT, 3);
			_cpu->setStop(false);
			break;
	}
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/platform_util.h"

#include <gtk/gtk.h>

#include "app/gtk_util.h"
#include "base/file_util.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/process_watcher.h"
#include "googleurl/src/gurl.h"

#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"

class Profile;

namespace platform_util {

// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const FilePath& full_path) {
  FilePath dir = full_path.DirName();
  if (!file_util::DirectoryExists(dir))
    return;

  Profile* profile;
  profile = BrowserList::GetLastActive()->profile();

  FileBrowseUI::OpenPopup(profile,
                          dir.value(),
                          FileBrowseUI::kPopupWidth,
                          FileBrowseUI::kPopupHeight);
}

void OpenItem(const FilePath& full_path) {
  std::string ext = full_path.Extension();
  // For things supported natively by the browser, we should open it
  // in a tab.
  if (ext == ".jpg" ||
      ext == ".jpeg" ||
      ext == ".png" ||
      ext == ".gif" ||
      ext == ".html" ||
      ext == ".htm") {
    std::string path;
    path = "file://";
    path += full_path.value();
    if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
      bool result = ChromeThread::PostTask(
          ChromeThread::UI, FROM_HERE,
          NewRunnableFunction(&OpenItem, full_path));
      DCHECK(result);
      return;
    }
    Browser* browser = BrowserList::GetLastActive();
    browser->AddTabWithURL(
        GURL(path), GURL(), PageTransition::LINK,
        true, -1, false, NULL);
    return;
  }
  if (ext == ".avi" ||
      ext == ".mp4" ||
      ext == ".mp3" ||
      ext == ".mkv" ||
      ext == ".ogg") {
    MediaPlayer* mediaplayer = MediaPlayer::Get();
    std::string url = "file://";
    url += full_path.value();
    GURL gurl(url);
    mediaplayer->EnqueueMediaURL(gurl);
    return;
  }
}

void OpenExternal(const GURL& url) {

}

}  // namespace platform_util
<commit_msg>Fixing opening files on chromeos.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/platform_util.h"

#include <gtk/gtk.h>

#include "app/gtk_util.h"
#include "base/file_util.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/process_watcher.h"
#include "googleurl/src/gurl.h"

#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/dom_ui/mediaplayer_ui.h"

class Profile;

namespace platform_util {

// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
void ShowItemInFolder(const FilePath& full_path) {
  FilePath dir = full_path.DirName();
  if (!file_util::DirectoryExists(dir))
    return;

  Profile* profile;
  profile = BrowserList::GetLastActive()->profile();

  FileBrowseUI::OpenPopup(profile,
                          dir.value(),
                          FileBrowseUI::kPopupWidth,
                          FileBrowseUI::kPopupHeight);
}

void OpenItem(const FilePath& full_path) {
  std::string ext = full_path.Extension();
  // For things supported natively by the browser, we should open it
  // in a tab.
  if (ext == ".jpg" ||
      ext == ".jpeg" ||
      ext == ".png" ||
      ext == ".gif" ||
      ext == ".html" ||
      ext == ".htm") {
    std::string path;
    path = "file://";
    path.append(full_path.value());
    if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {
      bool result = ChromeThread::PostTask(
          ChromeThread::UI, FROM_HERE,
          NewRunnableFunction(&OpenItem, full_path));
      DCHECK(result);
      return;
    }
    Browser* browser = BrowserList::GetLastActive();
    browser->AddTabWithURL(
        GURL(path), GURL(), PageTransition::LINK, -1, Browser::ADD_SELECTED,
        NULL, std::string());
    return;
  }
  if (ext == ".avi" ||
      ext == ".mp4" ||
      ext == ".mp3" ||
      ext == ".mkv" ||
      ext == ".ogg") {
    MediaPlayer* mediaplayer = MediaPlayer::Get();
    std::string url = "file://";
    url += full_path.value();
    GURL gurl(url);
    mediaplayer->EnqueueMediaURL(gurl);
    return;
  }
}

void OpenExternal(const GURL& url) {

}

}  // namespace platform_util
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/first_run_bubble.h"

#include "chrome/app/locales/locale_settings.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/options_window.h"
#include "chrome/browser/template_url_model.h"
#include "chrome/browser/views/standard_layout.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/event.h"
#include "chrome/views/label.h"
#include "chrome/views/native_button.h"
#include "chrome/views/window.h"

#include "chromium_strings.h"
#include "generated_resources.h"

namespace {

// How much extra padding to put around our content over what
// infobubble provides.
static const int kBubblePadding = 4;

// TODO(cpu): bug 1187517. It is possible that there is no default provider.
// we should make sure there is none at first run.
std::wstring GetDefaultSearchEngineName() {
  Browser* browser = BrowserList::GetLastActive();
  DCHECK(browser);
  const TemplateURL* const default_provider =
      browser->profile()->GetTemplateURLModel()->GetDefaultSearchProvider();
  DCHECK(default_provider);
  return default_provider->short_name();
}

}  // namespace

// Implements the client view inside the first run bubble. It is kind of a
// dialog-ish view, but is not a true dialog.
class FirstRunBubbleView : public ChromeViews::View,
                           public ChromeViews::NativeButton::Listener {
 public:
  explicit FirstRunBubbleView(FirstRunBubble* bubble_window)
      : bubble_window_(bubble_window),
        label1_(NULL),
        label2_(NULL),
        label3_(NULL),
        keep_button_(NULL),
        change_button_(NULL) {
    ChromeFont& font =
        ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::MediumFont);

    label1_ = new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_TITLE));
    label1_->SetFont(font.DeriveFont(3, ChromeFont::BOLD));
    label1_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);
    AddChildView(label1_);

    CSize ps;
    GetPreferredSize(&ps);

    label2_ =
        new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_SUBTEXT));
    label2_->SetMultiLine(true);
    label2_->SetFont(font);
    label2_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);
    label2_->SizeToFit(ps.cx - kBubblePadding * 2);
    AddChildView(label2_);

    std::wstring question_str
        = l10n_util::GetStringF(IDS_FR_BUBBLE_QUESTION,
                                GetDefaultSearchEngineName());
    label3_ = new ChromeViews::Label(question_str);
    label3_->SetMultiLine(true);
    label3_->SetFont(font);
    label3_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);
    label3_->SizeToFit(ps.cx - kBubblePadding * 2);
    AddChildView(label3_);

    std::wstring keep_str = l10n_util::GetStringF(IDS_FR_BUBBLE_OK,
                                                  GetDefaultSearchEngineName());
    keep_button_ = new ChromeViews::NativeButton(keep_str, true);
    keep_button_->SetListener(this);
    AddChildView(keep_button_);

    std::wstring change_str = l10n_util::GetString(IDS_FR_BUBBLE_CHANGE);
    change_button_ = new ChromeViews::NativeButton(change_str);
    change_button_->SetListener(this);
    AddChildView(change_button_);
  }

  // Overridden from ChromeViews::View.
  virtual void DidChangeBounds(const CRect& previous, const CRect& current) {
    Layout();
  }

  // Overridden from NativeButton::Listener.
  virtual void ButtonPressed(ChromeViews::NativeButton* sender) {
    bubble_window_->Close();
    if (change_button_ == sender) {
      Browser* browser = BrowserList::GetLastActive();
      if (browser) {
        ShowOptionsWindow(OPTIONS_PAGE_GENERAL, OPTIONS_GROUP_DEFAULT_SEARCH,
                          browser->profile());
      }
    }
  }

  // Overridden from ChromeViews::View.
  virtual void Layout() {
    CSize canvas;
    GetPreferredSize(&canvas);

    CSize pref_size;
    // The multiline business that follows is dirty hacks to get around
    // bug 1325257.
    label1_->SetMultiLine(false);
    label1_->GetPreferredSize(&pref_size);
    label1_->SetMultiLine(true);
    label1_->SizeToFit(canvas.cx - kBubblePadding * 2);
    label1_->SetBounds(kBubblePadding, kBubblePadding,
                       canvas.cx - kBubblePadding * 2,
                       pref_size.cy);

    int next_v_space = label1_->y() + pref_size.cy +
                       kRelatedControlSmallVerticalSpacing;

    label2_->GetPreferredSize(&pref_size);
    label2_->SetBounds(kBubblePadding, next_v_space,
                       canvas.cx - kBubblePadding * 2,
                       pref_size.cy);

    next_v_space = label2_->y() + label2_->height() +
                   kPanelSubVerticalSpacing;

    label3_->GetPreferredSize(&pref_size);
    label3_->SetBounds(kBubblePadding, next_v_space,
                       canvas.cx - kBubblePadding * 2,
                       pref_size.cy);

    change_button_->GetPreferredSize(&pref_size);
    change_button_->SetBounds(canvas.cx - pref_size.cx - kBubblePadding,
                              canvas.cy - pref_size.cy - kButtonVEdgeMargin,
                              pref_size.cx, pref_size.cy);

    keep_button_->GetPreferredSize(&pref_size);
    keep_button_->SetBounds(change_button_->x() - pref_size.cx -
                            kRelatedButtonHSpacing, change_button_->y(),
                            pref_size.cx, pref_size.cy);
  }

  virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {
    if (keep_button_)
      keep_button_->RequestFocus();
  }

  // Overridden from ChromeViews::View.
  virtual void GetPreferredSize(CSize *out) {
    DCHECK(out);
    *out = ChromeViews::Window::GetLocalizedContentsSize(
        IDS_FIRSTRUNBUBBLE_DIALOG_WIDTH_CHARS,
        IDS_FIRSTRUNBUBBLE_DIALOG_HEIGHT_LINES).ToSIZE();
  }

 private:
  FirstRunBubble* bubble_window_;
  ChromeViews::Label* label1_;
  ChromeViews::Label* label2_;
  ChromeViews::Label* label3_;
  ChromeViews::NativeButton* change_button_;
  ChromeViews::NativeButton* keep_button_;
  DISALLOW_EVIL_CONSTRUCTORS(FirstRunBubbleView);
};

// Keep the bubble around for kLingerTime milliseconds, to prevent accidental
// closure.
static const int kLingerTime = 1000;

void FirstRunBubble::OnActivate(UINT action, BOOL minimized, HWND window) {
  // We might get re-enabled right before we are closed (sequence is: we get
  // deactivated, we call close, before we are actually closed we get
  // reactivated). Don't do the disabling of the parent in such cases.
  if (action == WA_ACTIVE && !has_been_activated_) {
    has_been_activated_ = true;

    // Disable the browser to prevent accidental rapid clicks from closing the
    // bubble.
    ::EnableWindow(GetParent(), false);

    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        enable_window_method_factory_.NewRunnableMethod(
            &FirstRunBubble::EnableParent),
        kLingerTime);
  }
  InfoBubble::OnActivate(action, minimized, window);
}

void FirstRunBubble::InfoBubbleClosing(InfoBubble* info_bubble) {
  // Make sure our parent window is re-enabled.
  if (!IsWindowEnabled(GetParent()))
    ::EnableWindow(GetParent(), true);
  enable_window_method_factory_.RevokeAll();
}

FirstRunBubble* FirstRunBubble::Show(HWND parent_hwnd,
                                     const gfx::Rect& position_relative_to) {
  FirstRunBubble* window = new FirstRunBubble();
  ChromeViews::View* view = new FirstRunBubbleView(window);
  window->SetDelegate(window);
  window->Init(parent_hwnd, position_relative_to, view);
  BrowserWindow* frame = window->GetHostingWindow();
  DCHECK(frame);
  frame->InfoBubbleShowing();
  window->ShowWindow(SW_SHOW);
  return window;
}

void FirstRunBubble::EnableParent() {
  ::EnableWindow(GetParent(), true);
}

<commit_msg>Fix for a crash in the info bubble at first run - Null deref in GetDefaultSearchEngineName - This is a stopgap fix<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/first_run_bubble.h"

#include "chrome/app/locales/locale_settings.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/options_window.h"
#include "chrome/browser/template_url_model.h"
#include "chrome/browser/views/standard_layout.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/event.h"
#include "chrome/views/label.h"
#include "chrome/views/native_button.h"
#include "chrome/views/window.h"

#include "chromium_strings.h"
#include "generated_resources.h"

namespace {

// How much extra padding to put around our content over what
// infobubble provides.
static const int kBubblePadding = 4;

std::wstring GetDefaultSearchEngineName() {
  Browser* browser = BrowserList::GetLastActive();
  DCHECK(browser);
  const TemplateURL* const default_provider =
      browser->profile()->GetTemplateURLModel()->GetDefaultSearchProvider();
  if (!default_provider) {
    // TODO(cpu): bug 1187517. It is possible to have no default provider.
    // returning an empty string is a stopgap measure for the crash
    // http://code.google.com/p/chromium/issues/detail?id=2573
    return std::wstring();
  }
  return default_provider->short_name();
}

}  // namespace

// Implements the client view inside the first run bubble. It is kind of a
// dialog-ish view, but is not a true dialog.
class FirstRunBubbleView : public ChromeViews::View,
                           public ChromeViews::NativeButton::Listener {
 public:
  explicit FirstRunBubbleView(FirstRunBubble* bubble_window)
      : bubble_window_(bubble_window),
        label1_(NULL),
        label2_(NULL),
        label3_(NULL),
        keep_button_(NULL),
        change_button_(NULL) {
    ChromeFont& font =
        ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::MediumFont);

    label1_ = new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_TITLE));
    label1_->SetFont(font.DeriveFont(3, ChromeFont::BOLD));
    label1_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);
    AddChildView(label1_);

    CSize ps;
    GetPreferredSize(&ps);

    label2_ =
        new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_SUBTEXT));
    label2_->SetMultiLine(true);
    label2_->SetFont(font);
    label2_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);
    label2_->SizeToFit(ps.cx - kBubblePadding * 2);
    AddChildView(label2_);

    std::wstring question_str
        = l10n_util::GetStringF(IDS_FR_BUBBLE_QUESTION,
                                GetDefaultSearchEngineName());
    label3_ = new ChromeViews::Label(question_str);
    label3_->SetMultiLine(true);
    label3_->SetFont(font);
    label3_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);
    label3_->SizeToFit(ps.cx - kBubblePadding * 2);
    AddChildView(label3_);

    std::wstring keep_str = l10n_util::GetStringF(IDS_FR_BUBBLE_OK,
                                                  GetDefaultSearchEngineName());
    keep_button_ = new ChromeViews::NativeButton(keep_str, true);
    keep_button_->SetListener(this);
    AddChildView(keep_button_);

    std::wstring change_str = l10n_util::GetString(IDS_FR_BUBBLE_CHANGE);
    change_button_ = new ChromeViews::NativeButton(change_str);
    change_button_->SetListener(this);
    AddChildView(change_button_);
  }

  // Overridden from ChromeViews::View.
  virtual void DidChangeBounds(const CRect& previous, const CRect& current) {
    Layout();
  }

  // Overridden from NativeButton::Listener.
  virtual void ButtonPressed(ChromeViews::NativeButton* sender) {
    bubble_window_->Close();
    if (change_button_ == sender) {
      Browser* browser = BrowserList::GetLastActive();
      if (browser) {
        ShowOptionsWindow(OPTIONS_PAGE_GENERAL, OPTIONS_GROUP_DEFAULT_SEARCH,
                          browser->profile());
      }
    }
  }

  // Overridden from ChromeViews::View.
  virtual void Layout() {
    CSize canvas;
    GetPreferredSize(&canvas);

    CSize pref_size;
    // The multiline business that follows is dirty hacks to get around
    // bug 1325257.
    label1_->SetMultiLine(false);
    label1_->GetPreferredSize(&pref_size);
    label1_->SetMultiLine(true);
    label1_->SizeToFit(canvas.cx - kBubblePadding * 2);
    label1_->SetBounds(kBubblePadding, kBubblePadding,
                       canvas.cx - kBubblePadding * 2,
                       pref_size.cy);

    int next_v_space = label1_->y() + pref_size.cy +
                       kRelatedControlSmallVerticalSpacing;

    label2_->GetPreferredSize(&pref_size);
    label2_->SetBounds(kBubblePadding, next_v_space,
                       canvas.cx - kBubblePadding * 2,
                       pref_size.cy);

    next_v_space = label2_->y() + label2_->height() +
                   kPanelSubVerticalSpacing;

    label3_->GetPreferredSize(&pref_size);
    label3_->SetBounds(kBubblePadding, next_v_space,
                       canvas.cx - kBubblePadding * 2,
                       pref_size.cy);

    change_button_->GetPreferredSize(&pref_size);
    change_button_->SetBounds(canvas.cx - pref_size.cx - kBubblePadding,
                              canvas.cy - pref_size.cy - kButtonVEdgeMargin,
                              pref_size.cx, pref_size.cy);

    keep_button_->GetPreferredSize(&pref_size);
    keep_button_->SetBounds(change_button_->x() - pref_size.cx -
                            kRelatedButtonHSpacing, change_button_->y(),
                            pref_size.cx, pref_size.cy);
  }

  virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {
    if (keep_button_)
      keep_button_->RequestFocus();
  }

  // Overridden from ChromeViews::View.
  virtual void GetPreferredSize(CSize *out) {
    DCHECK(out);
    *out = ChromeViews::Window::GetLocalizedContentsSize(
        IDS_FIRSTRUNBUBBLE_DIALOG_WIDTH_CHARS,
        IDS_FIRSTRUNBUBBLE_DIALOG_HEIGHT_LINES).ToSIZE();
  }

 private:
  FirstRunBubble* bubble_window_;
  ChromeViews::Label* label1_;
  ChromeViews::Label* label2_;
  ChromeViews::Label* label3_;
  ChromeViews::NativeButton* change_button_;
  ChromeViews::NativeButton* keep_button_;
  DISALLOW_EVIL_CONSTRUCTORS(FirstRunBubbleView);
};

// Keep the bubble around for kLingerTime milliseconds, to prevent accidental
// closure.
static const int kLingerTime = 1000;

void FirstRunBubble::OnActivate(UINT action, BOOL minimized, HWND window) {
  // We might get re-enabled right before we are closed (sequence is: we get
  // deactivated, we call close, before we are actually closed we get
  // reactivated). Don't do the disabling of the parent in such cases.
  if (action == WA_ACTIVE && !has_been_activated_) {
    has_been_activated_ = true;

    // Disable the browser to prevent accidental rapid clicks from closing the
    // bubble.
    ::EnableWindow(GetParent(), false);

    MessageLoop::current()->PostDelayedTask(FROM_HERE,
        enable_window_method_factory_.NewRunnableMethod(
            &FirstRunBubble::EnableParent),
        kLingerTime);
  }
  InfoBubble::OnActivate(action, minimized, window);
}

void FirstRunBubble::InfoBubbleClosing(InfoBubble* info_bubble) {
  // Make sure our parent window is re-enabled.
  if (!IsWindowEnabled(GetParent()))
    ::EnableWindow(GetParent(), true);
  enable_window_method_factory_.RevokeAll();
}

FirstRunBubble* FirstRunBubble::Show(HWND parent_hwnd,
                                     const gfx::Rect& position_relative_to) {
  FirstRunBubble* window = new FirstRunBubble();
  ChromeViews::View* view = new FirstRunBubbleView(window);
  window->SetDelegate(window);
  window->Init(parent_hwnd, position_relative_to, view);
  BrowserWindow* frame = window->GetHostingWindow();
  DCHECK(frame);
  frame->InfoBubbleShowing();
  window->ShowWindow(SW_SHOW);
  return window;
}

void FirstRunBubble::EnableParent() {
  ::EnableWindow(GetParent(), true);
}

<|endoftext|>


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

#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"

// Reproduces https://code.google.com/p/chromium/issues/detail?id=279014

static const SkScalar kWidth = SkIntToScalar(640);
static const SkScalar kHeight = SkIntToScalar(480);
static const SkScalar kAngle = 0.305f;

// Renders a string art shape.
// The particular shape rendered can be controlled by adjusting kAngle, from 0 to 1

class StringArtGM : public skiagm::GM {
public:
    StringArtGM() {}

protected:
    virtual SkString onShortName() {
        return SkString("stringart");
    }

    virtual SkISize onISize() {
        return SkISize::Make(kWidth, kHeight);
    }

    virtual void onDraw(SkCanvas* canvas) {
        SkScalar angle = kAngle*SK_ScalarPI + SkScalarHalf(SK_ScalarPI);
        SkScalar size = SkMinScalar(kWidth, kHeight);
        SkPoint center = SkPoint::Make(SkScalarHalf(kWidth), SkScalarHalf(kHeight));
        SkScalar length = 5;
        SkScalar step = angle;

        SkPath path;
        path.moveTo(center);

        while (length < (SkScalarHalf(size) - 10.f))
        {
            SkPoint rp = SkPoint::Make(length*SkScalarCos(step) + center.fX,
                                       length*SkScalarSin(step) + center.fY);
            path.lineTo(rp);
            length += SkScalarDiv(angle, SkScalarHalf(SK_ScalarPI));
            step += angle;
        }
        path.close();

        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setColor(0xFF007700);

        canvas->drawPath(path, paint);
    }

private:
    typedef GM INHERITED;
};

DEF_GM( return new StringArtGM; )
<commit_msg>One more try at fixing warnings<commit_after>/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkPath.h"

// Reproduces https://code.google.com/p/chromium/issues/detail?id=279014

static const int kWidth = 640;
static const int kHeight = 480;
static const SkScalar kAngle = 0.305f;

// Renders a string art shape.
// The particular shape rendered can be controlled by adjusting kAngle, from 0 to 1

class StringArtGM : public skiagm::GM {
public:
    StringArtGM() {}

protected:
    virtual SkString onShortName() {
        return SkString("stringart");
    }

    virtual SkISize onISize() {
        return SkISize::Make(kWidth, kHeight);
    }

    virtual void onDraw(SkCanvas* canvas) {
        SkScalar angle = kAngle*SK_ScalarPI + SkScalarHalf(SK_ScalarPI);
        SkScalar size = SkIntToScalar(SkMin32(kWidth, kHeight));
        SkPoint center = SkPoint::Make(SkScalarHalf(kWidth), SkScalarHalf(kHeight));
        SkScalar length = 5;
        SkScalar step = angle;

        SkPath path;
        path.moveTo(center);

        while (length < (SkScalarHalf(size) - 10.f))
        {
            SkPoint rp = SkPoint::Make(length*SkScalarCos(step) + center.fX,
                                       length*SkScalarSin(step) + center.fY);
            path.lineTo(rp);
            length += SkScalarDiv(angle, SkScalarHalf(SK_ScalarPI));
            step += angle;
        }
        path.close();

        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setColor(0xFF007700);

        canvas->drawPath(path, paint);
    }

private:
    typedef GM INHERITED;
};

DEF_GM( return new StringArtGM; )
<|endoftext|>