<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.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
<commit_msg>Changing platform util for chromeos to open a gmail when the user clicks mailto<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 {

static const std::string kGmailComposeUrl =
    "https://mail.google.com/mail/?extsrc=mailto&url=";

// 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;
  }
}

static void OpenURL(const std::string& url) {
  Browser* browser = BrowserList::GetLastActive();
  browser->AddTabWithURL(
      GURL(url), GURL(), PageTransition::LINK, -1, Browser::ADD_SELECTED,
      NULL, std::string());
}

void OpenExternal(const GURL& url) {
  if (url.SchemeIs("mailto")) {
    std::string string_url = kGmailComposeUrl;
    string_url.append(url.spec());
    ChromeThread::PostTask(
        ChromeThread::UI, FROM_HERE, NewRunnableFunction(OpenURL, string_url));
  }
}

}  // namespace platform_util
<|endoftext|>


<commit_before>/*
 * Copyright 2006 Sony Computer Entertainment Inc.
 *
 * Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html
 *
 * 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.
 */

#include "daeWriter.h"

#include <dom/domCOLLADA.h>

#include <dom/domNode.h>
#include <dom/domConstants.h>

using namespace osgdae;

//MATRIX
void daeWriter::apply( osg::MatrixTransform &node )
{
#ifdef _DEBUG
    debugPrint( node );
#endif

    while ( lastDepth >= _nodePath.size() )
    {
        //We are not a child of previous node
        currentNode = daeSafeCast< domNode >( currentNode->getParentElement() );
        lastDepth--;
    }

    currentNode = daeSafeCast< domNode >(currentNode->createAndPlace( COLLADA_ELEMENT_NODE ) );
    currentNode->setId(getNodeName(node,"matrixTransform").c_str());

    domMatrix *mat = daeSafeCast< domMatrix >(currentNode->createAndPlace( COLLADA_ELEMENT_MATRIX ) );
    const osg::Matrix::value_type *mat_vals = node.getMatrix().ptr();
    //for ( int i = 0; i < 16; i++ )
    //{
    //  mat->getValue().append( mat_vals[i] );
    //}
    mat->getValue().append( mat_vals[0] );
    mat->getValue().append( mat_vals[4] );
    mat->getValue().append( mat_vals[8] );
    mat->getValue().append( mat_vals[12] );
    mat->getValue().append( mat_vals[1] );
    mat->getValue().append( mat_vals[5] );
    mat->getValue().append( mat_vals[9] );
    mat->getValue().append( mat_vals[13] );
    mat->getValue().append( mat_vals[2] );
    mat->getValue().append( mat_vals[6] );
    mat->getValue().append( mat_vals[10] );
    mat->getValue().append( mat_vals[14] );
    mat->getValue().append( mat_vals[3] );
    mat->getValue().append( mat_vals[7] );
    mat->getValue().append( mat_vals[11] );
    mat->getValue().append( mat_vals[15] );

    lastVisited = MATRIX;
    lastDepth = _nodePath.size();

    traverse( node );
}

//POSATT
void daeWriter::apply( osg::PositionAttitudeTransform &node )
{
#ifdef _DEBUG
    debugPrint( node );
#endif

    while ( lastDepth >= _nodePath.size() )
    {
        //We are not a child of previous node
        currentNode = daeSafeCast< domNode >( currentNode->getParentElement() );
        lastDepth--;
    }
    currentNode = daeSafeCast< domNode >(currentNode->createAndPlace( COLLADA_ELEMENT_NODE ) );
    currentNode->setId(getNodeName(node,"positionAttitudeTransform").c_str());

    const osg::Vec3 &pos = node.getPosition();
    const osg::Quat &q = node.getAttitude();
    const osg::Vec3 &s = node.getScale();

    if ( s.x() != 1 || s.y() != 1 || s.z() != 1 )
    {
        //make a scale
        domScale *scale = daeSafeCast< domScale >( currentNode->createAndPlace( COLLADA_ELEMENT_SCALE ) );
        scale->getValue().append( s.x() );
        scale->getValue().append( s.y() );
        scale->getValue().append( s.z() );
    }

    double angle;
    osg::Vec3 axis;
    q.getRotate( angle, axis );
    if ( angle != 0 )
    {
        //make a rotate
        domRotate *rot = daeSafeCast< domRotate >( currentNode->createAndPlace( COLLADA_ELEMENT_ROTATE ) );
        rot->getValue().append( axis.x() );
        rot->getValue().append( axis.y() );
        rot->getValue().append( axis.z() );
        rot->getValue().append( angle );
    }

    if ( pos.x() != 0 || pos.y() != 0 || pos.z() != 0 )
    {
        //make a translate
        domTranslate *trans = daeSafeCast< domTranslate >( currentNode->createAndPlace( COLLADA_ELEMENT_TRANSLATE ) );
        trans->getValue().append( pos.x() );
        trans->getValue().append( pos.y() );
        trans->getValue().append( pos.z() );
    }

    lastVisited = POSATT;
    lastDepth = _nodePath.size();

    traverse( node );
}

void daeWriter::apply( osg::Transform &node )
{
    osg::notify( osg::WARN ) << "some other transform type. Missing " << node.getNumChildren() << " children\n";
}

void daeWriter::apply( osg::CoordinateSystemNode &node )
{
    osg::notify( osg::WARN ) << "CoordinateSystemNode. Missing " << node.getNumChildren() << " children\n";
}
<commit_msg>From Panagiotis Koutsourakis, "We are using Open Scene Graph for an application and we need COLLADA support. While testing the pluggin we found a small bug and we are submitting a patch.<commit_after>/*
 * Copyright 2006 Sony Computer Entertainment Inc.
 *
 * Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html
 *
 * 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.
 */

#include "daeWriter.h"

#include <dom/domCOLLADA.h>

#include <dom/domNode.h>
#include <dom/domConstants.h>

using namespace osgdae;

//MATRIX
void daeWriter::apply( osg::MatrixTransform &node )
{
#ifdef _DEBUG
    debugPrint( node );
#endif

    while ( lastDepth >= _nodePath.size() )
    {
        //We are not a child of previous node
        currentNode = daeSafeCast< domNode >( currentNode->getParentElement() );
        lastDepth--;
    }

    currentNode = daeSafeCast< domNode >(currentNode->createAndPlace( COLLADA_ELEMENT_NODE ) );
    currentNode->setId(getNodeName(node,"matrixTransform").c_str());

    domMatrix *mat = daeSafeCast< domMatrix >(currentNode->createAndPlace( COLLADA_ELEMENT_MATRIX ) );
    const osg::Matrix::value_type *mat_vals = node.getMatrix().ptr();
    //for ( int i = 0; i < 16; i++ )
    //{
    //  mat->getValue().append( mat_vals[i] );
    //}
    mat->getValue().append( mat_vals[0] );
    mat->getValue().append( mat_vals[4] );
    mat->getValue().append( mat_vals[8] );
    mat->getValue().append( mat_vals[12] );
    mat->getValue().append( mat_vals[1] );
    mat->getValue().append( mat_vals[5] );
    mat->getValue().append( mat_vals[9] );
    mat->getValue().append( mat_vals[13] );
    mat->getValue().append( mat_vals[2] );
    mat->getValue().append( mat_vals[6] );
    mat->getValue().append( mat_vals[10] );
    mat->getValue().append( mat_vals[14] );
    mat->getValue().append( mat_vals[3] );
    mat->getValue().append( mat_vals[7] );
    mat->getValue().append( mat_vals[11] );
    mat->getValue().append( mat_vals[15] );

    lastVisited = MATRIX;
    lastDepth = _nodePath.size();

    traverse( node );
}

//POSATT
void daeWriter::apply( osg::PositionAttitudeTransform &node )
{
#ifdef _DEBUG
    debugPrint( node );
#endif

    while ( lastDepth >= _nodePath.size() )
    {
        //We are not a child of previous node
        currentNode = daeSafeCast< domNode >( currentNode->getParentElement() );
        lastDepth--;
    }
    currentNode = daeSafeCast< domNode >(currentNode->createAndPlace( COLLADA_ELEMENT_NODE ) );
    currentNode->setId(getNodeName(node,"positionAttitudeTransform").c_str());

    const osg::Vec3 &pos = node.getPosition();
    const osg::Quat &q = node.getAttitude();
    const osg::Vec3 &s = node.getScale();

    if ( s.x() != 1 || s.y() != 1 || s.z() != 1 )
    {
        //make a scale
        domScale *scale = daeSafeCast< domScale >( currentNode->createAndPlace( COLLADA_ELEMENT_SCALE ) );
        scale->getValue().append( s.x() );
        scale->getValue().append( s.y() );
        scale->getValue().append( s.z() );
    }

    double angle;
    osg::Vec3 axis;
    q.getRotate( angle, axis );
    if ( angle != 0 )
    {
        //make a rotate
        domRotate *rot = daeSafeCast< domRotate >( currentNode->createAndPlace( COLLADA_ELEMENT_ROTATE ) );
        rot->getValue().append( axis.x() );
        rot->getValue().append( axis.y() );
        rot->getValue().append( axis.z() );
        rot->getValue().append( osg::RadiansToDegrees(angle) );
    }

    if ( pos.x() != 0 || pos.y() != 0 || pos.z() != 0 )
    {
        //make a translate
        domTranslate *trans = daeSafeCast< domTranslate >( currentNode->createAndPlace( COLLADA_ELEMENT_TRANSLATE ) );
        trans->getValue().append( pos.x() );
        trans->getValue().append( pos.y() );
        trans->getValue().append( pos.z() );
    }

    lastVisited = POSATT;
    lastDepth = _nodePath.size();

    traverse( node );
}

void daeWriter::apply( osg::Transform &node )
{
    osg::notify( osg::WARN ) << "some other transform type. Missing " << node.getNumChildren() << " children\n";
}

void daeWriter::apply( osg::CoordinateSystemNode &node )
{
    osg::notify( osg::WARN ) << "CoordinateSystemNode. Missing " << node.getNumChildren() << " children\n";
}
<|endoftext|>


<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/browser/ui/auto_login_prompter.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/signin/token_service.h"
#include "chrome/browser/signin/token_service_factory.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/auto_login_parser/auto_login_parser.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "net/url_request/url_request.h"
#include "url/gurl.h"

using content::BrowserThread;
using content::WebContents;

namespace {

bool FetchUsernameThroughSigninManager(Profile* profile, std::string* output) {
  // In an incognito window, there may not be a profile sync service and/or
  // signin manager.
  if (!ProfileSyncServiceFactory::GetInstance()->HasProfileSyncService(
      profile)) {
    return false;
  }

  if (!TokenServiceFactory::GetForProfile(profile)->AreCredentialsValid())
    return false;

  SigninManagerBase* signin_manager =
      SigninManagerFactory::GetInstance()->GetForProfile(profile);
  if (!signin_manager)
    return false;

  *output = signin_manager->GetAuthenticatedUsername();
  return true;
}

}  // namespace

AutoLoginPrompter::AutoLoginPrompter(WebContents* web_contents,
                                     const Params& params,
                                     const GURL& url)
    : WebContentsObserver(web_contents),
      params_(params),
      url_(url),
      infobar_shown_(false) {
  if (!web_contents->IsLoading()) {
    // If the WebContents isn't loading a page, the load notification will never
    // be triggered.  Try adding the InfoBar now.
    AddInfoBarToWebContents();
  }
}

AutoLoginPrompter::~AutoLoginPrompter() {
}

// static
void AutoLoginPrompter::ShowInfoBarIfPossible(net::URLRequest* request,
                                              int child_id,
                                              int route_id) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAutologin))
      return;

  // See if the response contains the X-Auto-Login header.  If so, this was
  // a request for a login page, and the server is allowing the browser to
  // suggest auto-login, if available.
  Params params;
  // Currently we only accept GAIA credentials in Chrome.
  if (!auto_login_parser::ParserHeaderInResponse(
          request, auto_login_parser::ONLY_GOOGLE_COM, &params.header))
    return;

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ShowInfoBarUIThread,
                 params, request->url(), child_id, route_id));
}

// static
void AutoLoginPrompter::ShowInfoBarUIThread(Params params,
                                            const GURL& url,
                                            int child_id,
                                            int route_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  WebContents* web_contents = tab_util::GetWebContentsByID(child_id, route_id);
  if (!web_contents)
    return;

  Profile* profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());

  if (!profile->GetPrefs()->GetBoolean(prefs::kAutologinEnabled))
    return;

#if !defined(OS_ANDROID)
  // On Android, the username is fetched on the Java side from the
  // AccountManager provided by the platform.
  if (!FetchUsernameThroughSigninManager(profile, &params.username))
    return;
#endif

  // Make sure that |account|, if specified, matches the logged in user.
  // However, |account| is usually empty.
  if (!params.username.empty() && !params.header.account.empty() &&
      params.username != params.header.account)
    return;
  // We can't add the infobar just yet, since we need to wait for the tab to
  // finish loading.  If we don't, the info bar appears and then disappears
  // immediately.  Create an AutoLoginPrompter instance to listen for the
  // relevant notifications; it will delete itself.
  new AutoLoginPrompter(web_contents, params, url);
}

void AutoLoginPrompter::DidStopLoading(
    content::RenderViewHost* render_view_host) {
  AddInfoBarToWebContents();
  delete this;
}

void AutoLoginPrompter::WebContentsDestroyed(WebContents* web_contents) {
  // The WebContents was destroyed before the navigation completed.
  delete this;
}

void AutoLoginPrompter::AddInfoBarToWebContents() {
  if (infobar_shown_)
    return;

  InfoBarService* infobar_service =
      InfoBarService::FromWebContents(web_contents());
  // |infobar_service| is NULL for WebContents hosted in WebDialog.
  if (infobar_service) {
    AutoLoginInfoBarDelegate::Create(infobar_service, params_);
    infobar_shown_ = true;
  }
}
<commit_msg>Auto login prompter should not depend on TokenService.<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/browser/ui/auto_login_prompter.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/profile_oauth2_token_service.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/auto_login_parser/auto_login_parser.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "net/url_request/url_request.h"
#include "url/gurl.h"

using content::BrowserThread;
using content::WebContents;

namespace {

bool FetchUsernameThroughSigninManager(Profile* profile, std::string* output) {
  // In an incognito window these services are not available.
  ProfileOAuth2TokenService* token_service =
      ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
  if (!token_service || !token_service->RefreshTokenIsAvailable())
    return false;

  SigninManagerBase* signin_manager =
      SigninManagerFactory::GetInstance()->GetForProfile(profile);
  if (!signin_manager)
    return false;

  *output = signin_manager->GetAuthenticatedUsername();
  return true;
}

}  // namespace

AutoLoginPrompter::AutoLoginPrompter(WebContents* web_contents,
                                     const Params& params,
                                     const GURL& url)
    : WebContentsObserver(web_contents),
      params_(params),
      url_(url),
      infobar_shown_(false) {
  if (!web_contents->IsLoading()) {
    // If the WebContents isn't loading a page, the load notification will never
    // be triggered.  Try adding the InfoBar now.
    AddInfoBarToWebContents();
  }
}

AutoLoginPrompter::~AutoLoginPrompter() {
}

// static
void AutoLoginPrompter::ShowInfoBarIfPossible(net::URLRequest* request,
                                              int child_id,
                                              int route_id) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAutologin))
      return;

  // See if the response contains the X-Auto-Login header.  If so, this was
  // a request for a login page, and the server is allowing the browser to
  // suggest auto-login, if available.
  Params params;
  // Currently we only accept GAIA credentials in Chrome.
  if (!auto_login_parser::ParserHeaderInResponse(
          request, auto_login_parser::ONLY_GOOGLE_COM, &params.header))
    return;

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ShowInfoBarUIThread,
                 params, request->url(), child_id, route_id));
}

// static
void AutoLoginPrompter::ShowInfoBarUIThread(Params params,
                                            const GURL& url,
                                            int child_id,
                                            int route_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  WebContents* web_contents = tab_util::GetWebContentsByID(child_id, route_id);
  if (!web_contents)
    return;

  Profile* profile =
      Profile::FromBrowserContext(web_contents->GetBrowserContext());

  if (!profile->GetPrefs()->GetBoolean(prefs::kAutologinEnabled))
    return;

#if !defined(OS_ANDROID)
  // On Android, the username is fetched on the Java side from the
  // AccountManager provided by the platform.
  if (!FetchUsernameThroughSigninManager(profile, &params.username))
    return;
#endif

  // Make sure that |account|, if specified, matches the logged in user.
  // However, |account| is usually empty.
  if (!params.username.empty() && !params.header.account.empty() &&
      params.username != params.header.account)
    return;
  // We can't add the infobar just yet, since we need to wait for the tab to
  // finish loading.  If we don't, the info bar appears and then disappears
  // immediately.  Create an AutoLoginPrompter instance to listen for the
  // relevant notifications; it will delete itself.
  new AutoLoginPrompter(web_contents, params, url);
}

void AutoLoginPrompter::DidStopLoading(
    content::RenderViewHost* render_view_host) {
  AddInfoBarToWebContents();
  delete this;
}

void AutoLoginPrompter::WebContentsDestroyed(WebContents* web_contents) {
  // The WebContents was destroyed before the navigation completed.
  delete this;
}

void AutoLoginPrompter::AddInfoBarToWebContents() {
  if (infobar_shown_)
    return;

  InfoBarService* infobar_service =
      InfoBarService::FromWebContents(web_contents());
  // |infobar_service| is NULL for WebContents hosted in WebDialog.
  if (infobar_service) {
    AutoLoginInfoBarDelegate::Create(infobar_service, params_);
    infobar_shown_ = true;
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 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/ui/views/bubble/bubble.h"

#include <vector>

#include "chrome/browser/ui/views/bubble/border_contents.h"
#include "content/common/notification_service.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/gfx/color_utils.h"
#include "views/layout/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/client_view.h"
#include "views/window/window.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#endif

#if defined(OS_WIN)
#include "chrome/browser/ui/views/bubble/border_widget_win.h"
#endif

using std::vector;

// How long the fade should last for.
static const int kHideFadeDurationMS = 200;

// Background color of the bubble.
#if defined(OS_WIN)
const SkColor Bubble::kBackgroundColor =
    color_utils::GetSysSkColor(COLOR_WINDOW);
#else
// TODO(beng): source from theme provider.
const SkColor Bubble::kBackgroundColor = SK_ColorWHITE;
#endif

// BubbleDelegate ---------------------------------------------------------

std::wstring BubbleDelegate::accessible_name() {
  return L"";
}

// Bubble -----------------------------------------------------------------

// static
Bubble* Bubble::Show(views::Widget* parent,
                     const gfx::Rect& position_relative_to,
                     BubbleBorder::ArrowLocation arrow_location,
                     views::View* contents,
                     BubbleDelegate* delegate) {
  Bubble* bubble = new Bubble;
  bubble->InitBubble(parent, position_relative_to, arrow_location,
                     contents, delegate);
  return bubble;
}

#if defined(OS_CHROMEOS)
// static
Bubble* Bubble::ShowFocusless(
    views::Widget* parent,
    const gfx::Rect& position_relative_to,
    BubbleBorder::ArrowLocation arrow_location,
    views::View* contents,
    BubbleDelegate* delegate,
    bool show_while_screen_is_locked) {
  Bubble* bubble = new Bubble(views::Widget::InitParams::TYPE_POPUP,
                              show_while_screen_is_locked);
  bubble->InitBubble(parent, position_relative_to, arrow_location,
                     contents, delegate);
  return bubble;
}
#endif

void Bubble::Close() {
  if (show_status_ != kOpen)
    return;

  show_status_ = kClosing;

  if (fade_away_on_close_)
    FadeOut();
  else
    DoClose(false);
}

void Bubble::AnimationEnded(const ui::Animation* animation) {
  if (static_cast<int>(animation_->GetCurrentValue()) == 0) {
    // When fading out we just need to close the bubble at the end
    DoClose(false);
  } else {
#if defined(OS_WIN)
    // When fading in we need to remove the layered window style flag, since
    // that style prevents some bubble content from working properly.
    SetWindowLong(GWL_EXSTYLE, GetWindowLong(GWL_EXSTYLE) & ~WS_EX_LAYERED);
#endif
  }
}

void Bubble::AnimationProgressed(const ui::Animation* animation) {
#if defined(OS_WIN)
  // Set the opacity for the main contents window.
  unsigned char opacity = static_cast<unsigned char>(
      animation_->GetCurrentValue() * 255);
  SetLayeredWindowAttributes(GetNativeView(), 0,
      static_cast<byte>(opacity), LWA_ALPHA);
  contents_->SchedulePaint();

  // Also fade in/out the bubble border window.
  border_->SetOpacity(opacity);
  border_->border_contents()->SchedulePaint();
#else
  NOTIMPLEMENTED();
#endif
}

Bubble::Bubble()
    :
#if defined(OS_WIN)
      views::WidgetWin(new views::Widget),
#elif defined(TOOLKIT_USES_GTK)
      views::WidgetGtk(new views::Widget),
#endif
#if defined(TOOLKIT_USES_GTK)
      border_contents_(NULL),
#elif defined(OS_WIN)
      border_(NULL),
#endif
      delegate_(NULL),
      show_status_(kOpen),
      fade_away_on_close_(false),
#if defined(TOOLKIT_USES_GTK)
      type_(views::Widget::InitParams::TYPE_WINDOW),
#endif
#if defined(OS_CHROMEOS)
      show_while_screen_is_locked_(false),
#endif
      arrow_location_(BubbleBorder::NONE),
      contents_(NULL) {
}

#if defined(OS_CHROMEOS)
Bubble::Bubble(views::Widget::InitParams::Type type,
               bool show_while_screen_is_locked)
    : views::WidgetGtk(new views::Widget),
      border_contents_(NULL),
      delegate_(NULL),
      show_status_(kOpen),
      fade_away_on_close_(false),
      type_(type),
      show_while_screen_is_locked_(show_while_screen_is_locked),
      arrow_location_(BubbleBorder::NONE),
      contents_(NULL) {
}
#endif

Bubble::~Bubble() {
}

void Bubble::InitBubble(views::Widget* parent,
                        const gfx::Rect& position_relative_to,
                        BubbleBorder::ArrowLocation arrow_location,
                        views::View* contents,
                        BubbleDelegate* delegate) {
  delegate_ = delegate;
  position_relative_to_ = position_relative_to;
  arrow_location_ = arrow_location;
  contents_ = contents;

  // Create the main window.
#if defined(OS_WIN)
  views::Window* parent_window = parent->GetContainingWindow();
  if (parent_window)
    parent_window->DisableInactiveRendering();
  set_window_style(WS_POPUP | WS_CLIPCHILDREN);
  int extended_style = WS_EX_TOOLWINDOW;
  // During FadeIn we need to turn on the layered window style to deal with
  // transparency. This flag needs to be reset after fading in is complete.
  bool fade_in = delegate_ && delegate_->FadeInOnShow();
  if (fade_in)
    extended_style |= WS_EX_LAYERED;
  set_window_ex_style(extended_style);

  DCHECK(!border_);
  border_ = new BorderWidgetWin();

  if (fade_in) {
    border_->SetOpacity(0);
    GetWidget()->SetOpacity(0);
  }

  border_->InitBorderWidgetWin(CreateBorderContents(), parent->GetNativeView());
  border_->border_contents()->SetBackgroundColor(kBackgroundColor);

  // We make the BorderWidgetWin the owner of the Bubble HWND, so that the
  // latter is displayed on top of the former.
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
  params.parent = border_->GetNativeView();
  params.native_widget = this;
  GetWidget()->Init(params);

  SetWindowText(GetNativeView(), delegate_->accessible_name().c_str());
#elif defined(TOOLKIT_USES_GTK)
  views::Widget::InitParams params(type_);
  params.transparent = true;
  params.parent_widget = parent;
  params.native_widget = this;
  GetWidget()->Init(params);
#if defined(OS_CHROMEOS)
  {
    vector<int> params;
    params.push_back(show_while_screen_is_locked_ ? 1 : 0);
    chromeos::WmIpc::instance()->SetWindowType(
        GetNativeView(),
        chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
        &params);
  }
#endif
#endif

  // Create a View to hold the contents of the main window.
  views::View* contents_view = new views::View;
  // We add |contents_view| to ourselves before the AddChildView() call below so
  // that when |contents| gets added, it will already have a widget, and thus
  // any NativeButtons it creates in ViewHierarchyChanged() will be functional
  // (e.g. calling SetChecked() on checkboxes is safe).
  GetWidget()->SetContentsView(contents_view);
  // Adding |contents| as a child has to be done before we call
  // contents->GetPreferredSize() below, since some supplied views don't
  // actually initialize themselves until they're added to a hierarchy.
  contents_view->AddChildView(contents);

  // Calculate and set the bounds for all windows and views.
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to,
                                            arrow_location,
                                            contents->GetPreferredSize());

  // Make |contents| take up the entire contents view.
  contents_view->SetLayoutManager(new views::FillLayout);

  // Paint the background color behind the contents.
  contents_view->set_background(
      views::Background::CreateSolidBackground(kBackgroundColor));
#else
  // Create a view to paint the border and background.
  border_contents_ = CreateBorderContents();
  border_contents_->Init();
  border_contents_->SetBackgroundColor(kBackgroundColor);
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to,
      arrow_location, false, contents->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // This new view must be added before |contents| so it will paint under it.
  contents_view->AddChildViewAt(border_contents_, 0);

  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBoundsRect(
      gfx::Rect(gfx::Point(), window_bounds.size()));
  contents->SetBoundsRect(contents_bounds);
#endif
  GetWidget()->SetBounds(window_bounds);

  // Register the Escape accelerator for closing.
  GetWidget()->GetFocusManager()->RegisterAccelerator(
      views::Accelerator(ui::VKEY_ESCAPE, false, false, false), this);

  // Done creating the bubble.
  NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED,
                                         Source<Bubble>(this),
                                         NotificationService::NoDetails());

  // Show the window.
#if defined(OS_WIN)
  border_->ShowWindow(SW_SHOW);
  ShowWindow(SW_SHOW);
  if (fade_in)
    FadeIn();
#elif defined(TOOLKIT_USES_GTK)
  GetWidget()->Show();
#endif
}

BorderContents* Bubble::CreateBorderContents() {
  return new BorderContents();
}

void Bubble::SizeToContents() {
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to_,
                                            arrow_location_,
                                            contents_->GetPreferredSize());
#else
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to_,
      arrow_location_, false, contents_->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBoundsRect(
      gfx::Rect(gfx::Point(), window_bounds.size()));
  contents_->SetBoundsRect(contents_bounds);
#endif
  GetWidget()->SetBounds(window_bounds);
}

#if defined(OS_WIN)
void Bubble::OnActivate(UINT action, BOOL minimized, HWND window) {
  // The popup should close when it is deactivated.
  if (action == WA_INACTIVE) {
    GetWidget()->Close();
  } else if (action == WA_ACTIVE) {
    DCHECK(GetWidget()->GetRootView()->has_children());
    GetWidget()->GetRootView()->GetChildViewAt(0)->RequestFocus();
  }
}
#elif defined(TOOLKIT_USES_GTK)
void Bubble::IsActiveChanged() {
  if (!GetWidget()->IsActive())
    GetWidget()->Close();
}
#endif

void Bubble::DoClose(bool closed_by_escape) {
  if (show_status_ == kClosed)
    return;

  GetWidget()->GetFocusManager()->UnregisterAccelerator(
      views::Accelerator(ui::VKEY_ESCAPE, false, false, false), this);
  if (delegate_)
    delegate_->BubbleClosing(this, closed_by_escape);
  show_status_ = kClosed;
#if defined(OS_WIN)
  border_->Close();
#endif
#if defined(OS_WIN)
  WidgetWin::Close();
#elif defined(TOOLKIT_USES_GTK)
  WidgetGtk::Close();
#endif
}

void Bubble::FadeIn() {
  Fade(true);  // |fade_in|.
}

void Bubble::FadeOut() {
#if defined(OS_WIN)
  // The contents window cannot have the layered flag on by default, since its
  // content doesn't always work inside a layered window, but when animating it
  // is ok to set that style on the window for the purpose of fading it out.
  SetWindowLong(GWL_EXSTYLE, GetWindowLong(GWL_EXSTYLE) | WS_EX_LAYERED);
  // This must be the very next call, otherwise we can get flicker on close.
  SetLayeredWindowAttributes(GetNativeView(), 0,
      static_cast<byte>(255), LWA_ALPHA);
#endif

  Fade(false);  // |fade_in|.
}

void Bubble::Fade(bool fade_in) {
  animation_.reset(new ui::SlideAnimation(this));
  animation_->SetSlideDuration(kHideFadeDurationMS);
  animation_->SetTweenType(ui::Tween::LINEAR);

  animation_->Reset(fade_in ? 0.0 : 1.0);
  if (fade_in)
    animation_->Show();
  else
    animation_->Hide();
}

bool Bubble::AcceleratorPressed(const views::Accelerator& accelerator) {
  if (!delegate_ || delegate_->CloseOnEscape()) {
    DoClose(true);
    return true;
  }
  return false;
}
<commit_msg>Fix crash when installing extensions.<commit_after>// Copyright (c) 2011 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/ui/views/bubble/bubble.h"

#include <vector>

#include "chrome/browser/ui/views/bubble/border_contents.h"
#include "content/common/notification_service.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/gfx/color_utils.h"
#include "views/layout/fill_layout.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/client_view.h"
#include "views/window/window.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/wm_ipc.h"
#include "third_party/cros/chromeos_wm_ipc_enums.h"
#endif

#if defined(OS_WIN)
#include "chrome/browser/ui/views/bubble/border_widget_win.h"
#endif

using std::vector;

// How long the fade should last for.
static const int kHideFadeDurationMS = 200;

// Background color of the bubble.
#if defined(OS_WIN)
const SkColor Bubble::kBackgroundColor =
    color_utils::GetSysSkColor(COLOR_WINDOW);
#else
// TODO(beng): source from theme provider.
const SkColor Bubble::kBackgroundColor = SK_ColorWHITE;
#endif

// BubbleDelegate ---------------------------------------------------------

std::wstring BubbleDelegate::accessible_name() {
  return L"";
}

// Bubble -----------------------------------------------------------------

// static
Bubble* Bubble::Show(views::Widget* parent,
                     const gfx::Rect& position_relative_to,
                     BubbleBorder::ArrowLocation arrow_location,
                     views::View* contents,
                     BubbleDelegate* delegate) {
  Bubble* bubble = new Bubble;
  bubble->InitBubble(parent, position_relative_to, arrow_location,
                     contents, delegate);
  return bubble;
}

#if defined(OS_CHROMEOS)
// static
Bubble* Bubble::ShowFocusless(
    views::Widget* parent,
    const gfx::Rect& position_relative_to,
    BubbleBorder::ArrowLocation arrow_location,
    views::View* contents,
    BubbleDelegate* delegate,
    bool show_while_screen_is_locked) {
  Bubble* bubble = new Bubble(views::Widget::InitParams::TYPE_POPUP,
                              show_while_screen_is_locked);
  bubble->InitBubble(parent, position_relative_to, arrow_location,
                     contents, delegate);
  return bubble;
}
#endif

void Bubble::Close() {
  if (show_status_ != kOpen)
    return;

  show_status_ = kClosing;

  if (fade_away_on_close_)
    FadeOut();
  else
    DoClose(false);
}

void Bubble::AnimationEnded(const ui::Animation* animation) {
  if (static_cast<int>(animation_->GetCurrentValue()) == 0) {
    // When fading out we just need to close the bubble at the end
    DoClose(false);
  } else {
#if defined(OS_WIN)
    // When fading in we need to remove the layered window style flag, since
    // that style prevents some bubble content from working properly.
    SetWindowLong(GWL_EXSTYLE, GetWindowLong(GWL_EXSTYLE) & ~WS_EX_LAYERED);
#endif
  }
}

void Bubble::AnimationProgressed(const ui::Animation* animation) {
#if defined(OS_WIN)
  // Set the opacity for the main contents window.
  unsigned char opacity = static_cast<unsigned char>(
      animation_->GetCurrentValue() * 255);
  SetLayeredWindowAttributes(GetNativeView(), 0,
      static_cast<byte>(opacity), LWA_ALPHA);
  contents_->SchedulePaint();

  // Also fade in/out the bubble border window.
  border_->SetOpacity(opacity);
  border_->border_contents()->SchedulePaint();
#else
  NOTIMPLEMENTED();
#endif
}

Bubble::Bubble()
    :
#if defined(OS_WIN)
      views::WidgetWin(new views::Widget),
#elif defined(TOOLKIT_USES_GTK)
      views::WidgetGtk(new views::Widget),
#endif
#if defined(TOOLKIT_USES_GTK)
      border_contents_(NULL),
#elif defined(OS_WIN)
      border_(NULL),
#endif
      delegate_(NULL),
      show_status_(kOpen),
      fade_away_on_close_(false),
#if defined(TOOLKIT_USES_GTK)
      type_(views::Widget::InitParams::TYPE_WINDOW),
#endif
#if defined(OS_CHROMEOS)
      show_while_screen_is_locked_(false),
#endif
      arrow_location_(BubbleBorder::NONE),
      contents_(NULL) {
}

#if defined(OS_CHROMEOS)
Bubble::Bubble(views::Widget::InitParams::Type type,
               bool show_while_screen_is_locked)
    : views::WidgetGtk(new views::Widget),
      border_contents_(NULL),
      delegate_(NULL),
      show_status_(kOpen),
      fade_away_on_close_(false),
      type_(type),
      show_while_screen_is_locked_(show_while_screen_is_locked),
      arrow_location_(BubbleBorder::NONE),
      contents_(NULL) {
}
#endif

Bubble::~Bubble() {
}

void Bubble::InitBubble(views::Widget* parent,
                        const gfx::Rect& position_relative_to,
                        BubbleBorder::ArrowLocation arrow_location,
                        views::View* contents,
                        BubbleDelegate* delegate) {
  delegate_ = delegate;
  position_relative_to_ = position_relative_to;
  arrow_location_ = arrow_location;
  contents_ = contents;

  // Create the main window.
#if defined(OS_WIN)
  views::Window* parent_window = parent->GetContainingWindow();
  if (parent_window)
    parent_window->DisableInactiveRendering();
  set_window_style(WS_POPUP | WS_CLIPCHILDREN);
  int extended_style = WS_EX_TOOLWINDOW;
  // During FadeIn we need to turn on the layered window style to deal with
  // transparency. This flag needs to be reset after fading in is complete.
  bool fade_in = delegate_ && delegate_->FadeInOnShow();
  if (fade_in)
    extended_style |= WS_EX_LAYERED;
  set_window_ex_style(extended_style);

  DCHECK(!border_);
  border_ = new BorderWidgetWin();

  border_->InitBorderWidgetWin(CreateBorderContents(), parent->GetNativeView());
  border_->border_contents()->SetBackgroundColor(kBackgroundColor);

  // We make the BorderWidgetWin the owner of the Bubble HWND, so that the
  // latter is displayed on top of the former.
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
  params.parent = border_->GetNativeView();
  params.native_widget = this;
  GetWidget()->Init(params);

  if (fade_in) {
    border_->SetOpacity(0);
    GetWidget()->SetOpacity(0);
  }
  SetWindowText(GetNativeView(), delegate_->accessible_name().c_str());
#elif defined(TOOLKIT_USES_GTK)
  views::Widget::InitParams params(type_);
  params.transparent = true;
  params.parent_widget = parent;
  params.native_widget = this;
  GetWidget()->Init(params);
#if defined(OS_CHROMEOS)
  {
    vector<int> params;
    params.push_back(show_while_screen_is_locked_ ? 1 : 0);
    chromeos::WmIpc::instance()->SetWindowType(
        GetNativeView(),
        chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
        &params);
  }
#endif
#endif

  // Create a View to hold the contents of the main window.
  views::View* contents_view = new views::View;
  // We add |contents_view| to ourselves before the AddChildView() call below so
  // that when |contents| gets added, it will already have a widget, and thus
  // any NativeButtons it creates in ViewHierarchyChanged() will be functional
  // (e.g. calling SetChecked() on checkboxes is safe).
  GetWidget()->SetContentsView(contents_view);
  // Adding |contents| as a child has to be done before we call
  // contents->GetPreferredSize() below, since some supplied views don't
  // actually initialize themselves until they're added to a hierarchy.
  contents_view->AddChildView(contents);

  // Calculate and set the bounds for all windows and views.
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to,
                                            arrow_location,
                                            contents->GetPreferredSize());

  // Make |contents| take up the entire contents view.
  contents_view->SetLayoutManager(new views::FillLayout);

  // Paint the background color behind the contents.
  contents_view->set_background(
      views::Background::CreateSolidBackground(kBackgroundColor));
#else
  // Create a view to paint the border and background.
  border_contents_ = CreateBorderContents();
  border_contents_->Init();
  border_contents_->SetBackgroundColor(kBackgroundColor);
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to,
      arrow_location, false, contents->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // This new view must be added before |contents| so it will paint under it.
  contents_view->AddChildViewAt(border_contents_, 0);

  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBoundsRect(
      gfx::Rect(gfx::Point(), window_bounds.size()));
  contents->SetBoundsRect(contents_bounds);
#endif
  GetWidget()->SetBounds(window_bounds);

  // Register the Escape accelerator for closing.
  GetWidget()->GetFocusManager()->RegisterAccelerator(
      views::Accelerator(ui::VKEY_ESCAPE, false, false, false), this);

  // Done creating the bubble.
  NotificationService::current()->Notify(NotificationType::INFO_BUBBLE_CREATED,
                                         Source<Bubble>(this),
                                         NotificationService::NoDetails());

  // Show the window.
#if defined(OS_WIN)
  border_->ShowWindow(SW_SHOW);
  ShowWindow(SW_SHOW);
  if (fade_in)
    FadeIn();
#elif defined(TOOLKIT_USES_GTK)
  GetWidget()->Show();
#endif
}

BorderContents* Bubble::CreateBorderContents() {
  return new BorderContents();
}

void Bubble::SizeToContents() {
  gfx::Rect window_bounds;

#if defined(OS_WIN)
  // Initialize and position the border window.
  window_bounds = border_->SizeAndGetBounds(position_relative_to_,
                                            arrow_location_,
                                            contents_->GetPreferredSize());
#else
  gfx::Rect contents_bounds;
  border_contents_->SizeAndGetBounds(position_relative_to_,
      arrow_location_, false, contents_->GetPreferredSize(),
      &contents_bounds, &window_bounds);
  // |contents_view| has no layout manager, so we have to explicitly position
  // its children.
  border_contents_->SetBoundsRect(
      gfx::Rect(gfx::Point(), window_bounds.size()));
  contents_->SetBoundsRect(contents_bounds);
#endif
  GetWidget()->SetBounds(window_bounds);
}

#if defined(OS_WIN)
void Bubble::OnActivate(UINT action, BOOL minimized, HWND window) {
  // The popup should close when it is deactivated.
  if (action == WA_INACTIVE) {
    GetWidget()->Close();
  } else if (action == WA_ACTIVE) {
    DCHECK(GetWidget()->GetRootView()->has_children());
    GetWidget()->GetRootView()->GetChildViewAt(0)->RequestFocus();
  }
}
#elif defined(TOOLKIT_USES_GTK)
void Bubble::IsActiveChanged() {
  if (!GetWidget()->IsActive())
    GetWidget()->Close();
}
#endif

void Bubble::DoClose(bool closed_by_escape) {
  if (show_status_ == kClosed)
    return;

  GetWidget()->GetFocusManager()->UnregisterAccelerator(
      views::Accelerator(ui::VKEY_ESCAPE, false, false, false), this);
  if (delegate_)
    delegate_->BubbleClosing(this, closed_by_escape);
  show_status_ = kClosed;
#if defined(OS_WIN)
  border_->Close();
#endif
#if defined(OS_WIN)
  WidgetWin::Close();
#elif defined(TOOLKIT_USES_GTK)
  WidgetGtk::Close();
#endif
}

void Bubble::FadeIn() {
  Fade(true);  // |fade_in|.
}

void Bubble::FadeOut() {
#if defined(OS_WIN)
  // The contents window cannot have the layered flag on by default, since its
  // content doesn't always work inside a layered window, but when animating it
  // is ok to set that style on the window for the purpose of fading it out.
  SetWindowLong(GWL_EXSTYLE, GetWindowLong(GWL_EXSTYLE) | WS_EX_LAYERED);
  // This must be the very next call, otherwise we can get flicker on close.
  SetLayeredWindowAttributes(GetNativeView(), 0,
      static_cast<byte>(255), LWA_ALPHA);
#endif

  Fade(false);  // |fade_in|.
}

void Bubble::Fade(bool fade_in) {
  animation_.reset(new ui::SlideAnimation(this));
  animation_->SetSlideDuration(kHideFadeDurationMS);
  animation_->SetTweenType(ui::Tween::LINEAR);

  animation_->Reset(fade_in ? 0.0 : 1.0);
  if (fade_in)
    animation_->Show();
  else
    animation_->Hide();
}

bool Bubble::AcceleratorPressed(const views::Accelerator& accelerator) {
  if (!delegate_ || delegate_->CloseOnEscape()) {
    DoClose(true);
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AppView.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 17:08:16 $
 *
 *  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): Ocke Janssen
 *
 *
 ************************************************************************/
#ifndef DBAUI_APPVIEW_HXX
#define DBAUI_APPVIEW_HXX

#ifndef DBAUI_DATAVIEW_HXX
#include "dataview.hxx"
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
#ifndef DBAUI_APPELEMENTTYPE_HXX
#include "AppElementType.hxx"
#endif

namespace com{ namespace sun { namespace star { namespace beans    { class XPropertySet; } } } };
namespace com{ namespace sun { namespace star { namespace frame    { class XController; } } } };
class Control;
class SvLBoxEntry;

namespace dbaui
{
    class IApplicationElementNotification;
    class IControlActionListener;
    class IContainerFoundListener;
    class IViewChangeListener;
    class OApplicationView;
    class OApplicationDetailView;
    class OApplicationSwapWindow;
    class OTitleWindow;
    //==================================================================
    class OAppBorderWindow : public Window
    {
        OTitleWindow*                       m_pPanel;
        OApplicationDetailView*             m_pDetailView;
        OApplicationView*                   m_pView;

        void ImplInitSettings();
    protected:
        // Window
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
    public:
        OAppBorderWindow(OApplicationView* _pParent);
        virtual ~OAppBorderWindow();

        // window overloads
        virtual void GetFocus();
        virtual void Resize();

        OApplicationView*       getView() const;
        OApplicationSwapWindow* getPanel() const;
        OApplicationDetailView* getDetailView() const;
    };
    //==================================================================
    class OApplicationView : public ODataView
                            ,public IClipboardTest
                            ,public ::utl::OEventListenerAdapter
    {
        enum ChildFocusState
        {
            PANELSWAP,
            DETAIL,
            NONE
        };
    private:
        ::com::sun::star::lang::Locale      m_aLocale;
        ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XController>
                                            m_xController;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
                                            m_xObject;
        OAppBorderWindow*                   m_pWin;
        IApplicationElementNotification*    m_pElementNotification;
        IControlActionListener*             m_pActonListener;
        IContainerFoundListener*            m_pContainerListener;
        IViewChangeListener*                m_pViewChangeListener;
        ChildFocusState                     m_eChildFocus;

        IClipboardTest* getActiveChild() const;

        void ImplInitSettings();
    protected:

        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

        // Window
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
    public:
        OApplicationView(   Window* pParent
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&
                            ,IController* _pIController
                            ,IApplicationElementNotification*   _pController
                            ,IControlActionListener*            _pActonListener
                            ,IContainerFoundListener*           _pContainerListener
                            ,IViewChangeListener*               _pViewChangeListener
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController>& _xController
                            );
        virtual ~OApplicationView();

        /** automatically creates mnemonics for the icon/texts in our left hand side panel
        */
        void    createIconAutoMnemonics();

        // window overloads
        virtual long PreNotify( NotifyEvent& rNEvt );
        virtual void GetFocus();

        inline IApplicationElementNotification*         getElementNotification() const { return m_pElementNotification; }
        inline IControlActionListener*                  getActionListener() const { return m_pActonListener; }
        inline IContainerFoundListener*                 getContainerListener() const { return m_pContainerListener; }
        inline IViewChangeListener*                     getViewChangeListener() const { return m_pViewChangeListener; }
        inline const ::com::sun::star::lang::Locale&    getLocale() const { return m_aLocale;}
        inline ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XController> getController() const { return m_xController; }

        // IClipboardTest
        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
        virtual void copy();
        virtual void cut();
        virtual void paste();

        /// get the left panel
        inline OApplicationSwapWindow*  getPanel()      const { return m_pWin->getPanel(); }
        /// get the detail page
        inline OApplicationDetailView*  getDetailView() const { return m_pWin->getDetailView(); }

        /** return the qualified name.
            @param  _pEntry
                The entry of a table, or query, form, report to get the qualified name.
                If the entry is <NULL/>, the first selected is chosen.
            @param  _xMetaData
                The meta data are used to create the table name, otherwise this may also be <NULL/>
            @return
                the qualified name
        */
        ::rtl::OUString getQualifiedName(SvLBoxEntry* _pEntry
                                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData) const;

        /** returns if an entry is a leaf
            @param _pEntry
                The entry to check
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;

        /** returns if one of the selected entries is a leaf
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isALeafSelected() const;

        /** select all entries in the detail page
        */
        void selectAll();

        /// returns <TRUE/> if it sorts ascending
        sal_Bool isSortUp() const;

        /// sort the entries in the detail page down
        void sortDown();

        /// sort the entries in the detail page up
        void sortUp();

        /// returns <TRUE/> when a detail page was filled
        sal_Bool isFilled() const;

        /// return the element of currently select entry
        ElementType getElementType() const;

        /// returns the count of entries
        sal_Int32 getElementCount();

        /// returns the count of selected entries
        sal_Int32 getSelectionCount();

        /** clears the detail page and the selection on the left side.
            @param  _bTaskAlso
                If <TRUE/> the task window will also be cleared.
        */
        void clearPages(sal_Bool _bTaskAlso = sal_True);

        /** returns the element names which are selected
            @param  _rNames
                The list will be filled.
            @param  _xMetaData
                Will be used when the table list should be filled.
        */
        void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData = NULL) const;

        /** adds a new object to the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the object to be inserted
            @param  _rObject
                The object to add.
            @param  _rxConn
                If we insert a table, the connection must be set.
        */
        SvLBoxEntry* elementAdded(ElementType _eType
                        ,const ::rtl::OUString& _rName
                        ,const ::com::sun::star::uno::Any& _rObject
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);

        /** replaces a objects name with a new one
            @param  _eType
                The type where the entry shold be appended.
            @param  _rOldName
                The old name of the object to be replaced
            @param  _rNewName
                The new name of the object to be replaced
            @param  _rxConn
                If we insert a table, the connection must be set.
        */
        void elementReplaced(ElementType eType
                        ,const ::rtl::OUString& _rOldName
                        ,const ::rtl::OUString& _rNewName
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);

        /** removes an element from the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the element to be removed.
            @param  _rxConn
                If we remove a table, the connection must be set.
        */
        void elementRemoved(ElementType _eType
                            ,const ::rtl::OUString& _rName
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);

        /** clears the selection in the icon choice control and calls the handler
        */
        void clearSelection();

        /** changes the container which should be displayed. The select handler will also be called.
            @param  _eType
                Which container to show.
        */
        void changeContainer(ElementType _eType);

        /// returns the preview mode
        PreviewMode getPreviewMode();

        /// <TRUE/> if the preview is enabled
        sal_Bool isPreviewEnabled();

        /// switches the current preview
        void switchPreview();

        /** switches to the given preview mode
            @param  _eMode
                the mode to set for the preview
        */
        void switchPreview(PreviewMode _eMode);

        /** shows the Preview of the content when it is enabled.
            @param  _xContent
                The content which must support the "preview" command.
        */
        void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);

        /** shows the Preview of a table or query
            @param  _sDataSourceName
                the name of the data source
            @param  _xConnection
                the connection which will be shared
            @param  _sName
                the name of table or query
            @param  _bTable
                <TRUE/> if it is a table, otherwise <FALSE/>
            @return void
        */
        void showPreview(   const ::rtl::OUString& _sDataSourceName,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,
                            const ::rtl::OUString& _sName,
                            sal_Bool _bTable);

        SvLBoxEntry* getEntry( const Point& _aPosPixel ) const;

        /** disable the controls
            @param  _bDisable
                if <TRUE/> then the controls will be disabled otherwise they will be enabled.
        */
        void disableControls(sal_Bool _bDisable);

        DECL_LINK( SwitchHdl, Accelerator* );
    };
}
#endif // DBAUI_APPVIEW_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.142); FILE MERGED 2005/09/05 17:33:09 rt 1.6.142.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AppView.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:23:13 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBAUI_APPVIEW_HXX
#define DBAUI_APPVIEW_HXX

#ifndef DBAUI_DATAVIEW_HXX
#include "dataview.hxx"
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
#ifndef DBAUI_APPELEMENTTYPE_HXX
#include "AppElementType.hxx"
#endif

namespace com{ namespace sun { namespace star { namespace beans    { class XPropertySet; } } } };
namespace com{ namespace sun { namespace star { namespace frame    { class XController; } } } };
class Control;
class SvLBoxEntry;

namespace dbaui
{
    class IApplicationElementNotification;
    class IControlActionListener;
    class IContainerFoundListener;
    class IViewChangeListener;
    class OApplicationView;
    class OApplicationDetailView;
    class OApplicationSwapWindow;
    class OTitleWindow;
    //==================================================================
    class OAppBorderWindow : public Window
    {
        OTitleWindow*                       m_pPanel;
        OApplicationDetailView*             m_pDetailView;
        OApplicationView*                   m_pView;

        void ImplInitSettings();
    protected:
        // Window
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
    public:
        OAppBorderWindow(OApplicationView* _pParent);
        virtual ~OAppBorderWindow();

        // window overloads
        virtual void GetFocus();
        virtual void Resize();

        OApplicationView*       getView() const;
        OApplicationSwapWindow* getPanel() const;
        OApplicationDetailView* getDetailView() const;
    };
    //==================================================================
    class OApplicationView : public ODataView
                            ,public IClipboardTest
                            ,public ::utl::OEventListenerAdapter
    {
        enum ChildFocusState
        {
            PANELSWAP,
            DETAIL,
            NONE
        };
    private:
        ::com::sun::star::lang::Locale      m_aLocale;
        ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XController>
                                            m_xController;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >
                                            m_xObject;
        OAppBorderWindow*                   m_pWin;
        IApplicationElementNotification*    m_pElementNotification;
        IControlActionListener*             m_pActonListener;
        IContainerFoundListener*            m_pContainerListener;
        IViewChangeListener*                m_pViewChangeListener;
        ChildFocusState                     m_eChildFocus;

        IClipboardTest* getActiveChild() const;

        void ImplInitSettings();
    protected:

        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

        // Window
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
    public:
        OApplicationView(   Window* pParent
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&
                            ,IController* _pIController
                            ,IApplicationElementNotification*   _pController
                            ,IControlActionListener*            _pActonListener
                            ,IContainerFoundListener*           _pContainerListener
                            ,IViewChangeListener*               _pViewChangeListener
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController>& _xController
                            );
        virtual ~OApplicationView();

        /** automatically creates mnemonics for the icon/texts in our left hand side panel
        */
        void    createIconAutoMnemonics();

        // window overloads
        virtual long PreNotify( NotifyEvent& rNEvt );
        virtual void GetFocus();

        inline IApplicationElementNotification*         getElementNotification() const { return m_pElementNotification; }
        inline IControlActionListener*                  getActionListener() const { return m_pActonListener; }
        inline IContainerFoundListener*                 getContainerListener() const { return m_pContainerListener; }
        inline IViewChangeListener*                     getViewChangeListener() const { return m_pViewChangeListener; }
        inline const ::com::sun::star::lang::Locale&    getLocale() const { return m_aLocale;}
        inline ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XController> getController() const { return m_xController; }

        // IClipboardTest
        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
        virtual void copy();
        virtual void cut();
        virtual void paste();

        /// get the left panel
        inline OApplicationSwapWindow*  getPanel()      const { return m_pWin->getPanel(); }
        /// get the detail page
        inline OApplicationDetailView*  getDetailView() const { return m_pWin->getDetailView(); }

        /** return the qualified name.
            @param  _pEntry
                The entry of a table, or query, form, report to get the qualified name.
                If the entry is <NULL/>, the first selected is chosen.
            @param  _xMetaData
                The meta data are used to create the table name, otherwise this may also be <NULL/>
            @return
                the qualified name
        */
        ::rtl::OUString getQualifiedName(SvLBoxEntry* _pEntry
                                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData) const;

        /** returns if an entry is a leaf
            @param _pEntry
                The entry to check
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;

        /** returns if one of the selected entries is a leaf
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isALeafSelected() const;

        /** select all entries in the detail page
        */
        void selectAll();

        /// returns <TRUE/> if it sorts ascending
        sal_Bool isSortUp() const;

        /// sort the entries in the detail page down
        void sortDown();

        /// sort the entries in the detail page up
        void sortUp();

        /// returns <TRUE/> when a detail page was filled
        sal_Bool isFilled() const;

        /// return the element of currently select entry
        ElementType getElementType() const;

        /// returns the count of entries
        sal_Int32 getElementCount();

        /// returns the count of selected entries
        sal_Int32 getSelectionCount();

        /** clears the detail page and the selection on the left side.
            @param  _bTaskAlso
                If <TRUE/> the task window will also be cleared.
        */
        void clearPages(sal_Bool _bTaskAlso = sal_True);

        /** returns the element names which are selected
            @param  _rNames
                The list will be filled.
            @param  _xMetaData
                Will be used when the table list should be filled.
        */
        void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData>& _xMetaData = NULL) const;

        /** adds a new object to the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the object to be inserted
            @param  _rObject
                The object to add.
            @param  _rxConn
                If we insert a table, the connection must be set.
        */
        SvLBoxEntry* elementAdded(ElementType _eType
                        ,const ::rtl::OUString& _rName
                        ,const ::com::sun::star::uno::Any& _rObject
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);

        /** replaces a objects name with a new one
            @param  _eType
                The type where the entry shold be appended.
            @param  _rOldName
                The old name of the object to be replaced
            @param  _rNewName
                The new name of the object to be replaced
            @param  _rxConn
                If we insert a table, the connection must be set.
        */
        void elementReplaced(ElementType eType
                        ,const ::rtl::OUString& _rOldName
                        ,const ::rtl::OUString& _rNewName
                        ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn = NULL);

        /** removes an element from the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the element to be removed.
            @param  _rxConn
                If we remove a table, the connection must be set.
        */
        void elementRemoved(ElementType _eType
                            ,const ::rtl::OUString& _rName
                            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);

        /** clears the selection in the icon choice control and calls the handler
        */
        void clearSelection();

        /** changes the container which should be displayed. The select handler will also be called.
            @param  _eType
                Which container to show.
        */
        void changeContainer(ElementType _eType);

        /// returns the preview mode
        PreviewMode getPreviewMode();

        /// <TRUE/> if the preview is enabled
        sal_Bool isPreviewEnabled();

        /// switches the current preview
        void switchPreview();

        /** switches to the given preview mode
            @param  _eMode
                the mode to set for the preview
        */
        void switchPreview(PreviewMode _eMode);

        /** shows the Preview of the content when it is enabled.
            @param  _xContent
                The content which must support the "preview" command.
        */
        void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);

        /** shows the Preview of a table or query
            @param  _sDataSourceName
                the name of the data source
            @param  _xConnection
                the connection which will be shared
            @param  _sName
                the name of table or query
            @param  _bTable
                <TRUE/> if it is a table, otherwise <FALSE/>
            @return void
        */
        void showPreview(   const ::rtl::OUString& _sDataSourceName,
                            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,
                            const ::rtl::OUString& _sName,
                            sal_Bool _bTable);

        SvLBoxEntry* getEntry( const Point& _aPosPixel ) const;

        /** disable the controls
            @param  _bDisable
                if <TRUE/> then the controls will be disabled otherwise they will be enabled.
        */
        void disableControls(sal_Bool _bDisable);

        DECL_LINK( SwitchHdl, Accelerator* );
    };
}
#endif // DBAUI_APPVIEW_HXX

<|endoftext|>


<commit_before>#include <string>
#include <utility>

#include <ros/ros.h>
#include <controller_manager/controller_manager.h>
#include <hardware_interface/joint_command_interface.h> // for PositionJointInterface
#include <hardware_interface/joint_state_interface.h>
#include <hardware_interface/robot_hw.h>

class Arcsys2HW
: public hardware_interface::RobotHW
{
public:
  Arcsys2HW();
  void read();
  void write();
  ros::Time getTime() const;
  ros::Duration getPeriod() const;
private:
  static constexpr std::size_t JOINT_COUNT {6};
  hardware_interface::JointStateInterface joint_state_interface_;
  hardware_interface::PositionJointInterface joint_position_interface_;
  double pos_[JOINT_COUNT];
  double vel_[JOINT_COUNT];
  double eff_[JOINT_COUNT];
  double cmd_[JOINT_COUNT];
};

int main(int argc, char *argv[])
{
  ros::init(argc, argv, "arcsys2_control_node");

  Arcsys2HW robot {};
  controller_manager::ControllerManager cm {&robot};

  ros::Rate rate(1.0 / robot.getPeriod().toSec());
  ros::AsyncSpinner spinner {1};

  spinner.start();
  while(ros::ok())
  {
    robot.read();
    cm.update(robot.getTime(), robot.getPeriod());
    robot.write();
    rate.sleep();
  }
  spinner.stop();

  return 0;
}

inline Arcsys2HW::Arcsys2HW()
: joint_state_interface_ {},
  joint_position_interface_ {},
  cmd_ {},
  pos_ {},
  vel_ {},
  eff_ {}
{
  // [input] connect and register the joint state interface
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"rail_to_shaft_joint", &pos_[0], &vel_[0], &eff_[0]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"shaft_to_arm0_joint", &pos_[1], &vel_[1], &eff_[1]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm0_to_arm1_joint", &pos_[2], &vel_[2], &eff_[2]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm1_to_arm2_joint", &pos_[3], &vel_[3], &eff_[3]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm2_to_effector_base_joint", &pos_[4], &vel_[4], &eff_[4]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"effector_base_to_effector_end_joint", &pos_[5], &vel_[5], &eff_[5]});

  registerInterface(&joint_state_interface_);

  // [output] connect and register the joint position interface
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("rail_to_shaft_joint"), &cmd_[0]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("shaft_to_arm0_joint"), &cmd_[1]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm0_to_arm1_joint"), &cmd_[2]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm1_to_arm2_joint"), &cmd_[3]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm2_to_effector_base_joint"), &cmd_[4]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("effector_base_to_effector_end_joint"), &cmd_[5]});

  registerInterface(&joint_position_interface_);
}

inline void Arcsys2HW::read()
{
  for (std::size_t i {0}; i < 6; i++)
    ROS_INFO_STREAM("cmd[" << i << "]: "  << cmd_[i]);
}

inline void Arcsys2HW::write()
{
  for (std::size_t i {0}; i < 6; i++)
    pos_[i] = cmd_[i];
}

inline ros::Time Arcsys2HW::getTime() const
{
  return ros::Time::now();
}

inline ros::Duration Arcsys2HW::getPeriod() const
{
  return ros::Duration(0.01);
}
<commit_msg>Add velocity joint interface<commit_after>#include <string>
#include <utility>

#include <ros/ros.h>
#include <controller_manager/controller_manager.h>
#include <hardware_interface/joint_command_interface.h> // for PositionJointInterface
#include <hardware_interface/joint_state_interface.h>
#include <hardware_interface/robot_hw.h>

class Arcsys2HW
: public hardware_interface::RobotHW
{
public:
  Arcsys2HW();
  void read();
  void write();
  ros::Time getTime() const;
  ros::Duration getPeriod() const;
private:
  static constexpr std::size_t JOINT_COUNT {6};
  hardware_interface::JointStateInterface joint_state_interface_;
  hardware_interface::PositionJointInterface joint_position_interface_;
  hardware_interface::VelocityJointInterface joint_velocity_interface_;
  double pos_[JOINT_COUNT];
  double vel_[JOINT_COUNT];
  double eff_[JOINT_COUNT];
  double cmd_[JOINT_COUNT];
};

int main(int argc, char *argv[])
{
  ros::init(argc, argv, "arcsys2_control_node");

  Arcsys2HW robot {};
  controller_manager::ControllerManager cm {&robot};

  ros::Rate rate(1.0 / robot.getPeriod().toSec());
  ros::AsyncSpinner spinner {1};

  spinner.start();
  while(ros::ok())
  {
    robot.read();
    cm.update(robot.getTime(), robot.getPeriod());
    robot.write();
    rate.sleep();
  }
  spinner.stop();

  return 0;
}

inline Arcsys2HW::Arcsys2HW()
: joint_state_interface_ {},
  joint_position_interface_ {},
  joint_velocity_interface_ {},
  cmd_ {},
  pos_ {},
  vel_ {},
  eff_ {}
{
  // [input] connect and register the joint state interface
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"rail_to_shaft_joint", &pos_[0], &vel_[0], &eff_[0]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"shaft_to_arm0_joint", &pos_[1], &vel_[1], &eff_[1]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm0_to_arm1_joint", &pos_[2], &vel_[2], &eff_[2]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm1_to_arm2_joint", &pos_[3], &vel_[3], &eff_[3]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"arm2_to_effector_base_joint", &pos_[4], &vel_[4], &eff_[4]});
  joint_state_interface_.registerHandle(hardware_interface::JointStateHandle {"effector_base_to_effector_end_joint", &pos_[5], &vel_[5], &eff_[5]});

  registerInterface(&joint_state_interface_);

  // [output] connect and register the joint position interface
  joint_velocity_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("rail_to_shaft_joint"), &cmd_[0]});
  joint_velocity_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("shaft_to_arm0_joint"), &cmd_[1]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm0_to_arm1_joint"), &cmd_[2]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm1_to_arm2_joint"), &cmd_[3]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("arm2_to_effector_base_joint"), &cmd_[4]});
  joint_position_interface_.registerHandle(hardware_interface::JointHandle {joint_state_interface_.getHandle("effector_base_to_effector_end_joint"), &cmd_[5]});

  registerInterface(&joint_position_interface_);
}

inline void Arcsys2HW::read()
{
  for (std::size_t i {0}; i < 6; i++)
    ROS_INFO_STREAM("cmd[" << i << "]: "  << cmd_[i]);
}

inline void Arcsys2HW::write()
{
  for (std::size_t i {0}; i < 6; i++)
    pos_[i] = cmd_[i];
}

inline ros::Time Arcsys2HW::getTime() const
{
  return ros::Time::now();
}

inline ros::Duration Arcsys2HW::getPeriod() const
{
  return ros::Duration(0.01);
}
<|endoftext|>


<commit_before>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * 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 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "accounts-list-model.h"

#include "account-item.h"

#include <kdebug.h>

#include <TelepathyQt4/Client/Account>

AccountsListModel::AccountsListModel(QObject *parent)
 : QAbstractListModel(parent)
{
    m_unreadyAccounts.clear();
    m_readyAccounts.clear();
}

AccountsListModel::~AccountsListModel()
{
    // TODO: Implement me!
}

int AccountsListModel::rowCount(const QModelIndex &index) const
{
    // TODO: Implement me!
    return 0;
}

QVariant AccountsListModel::data(const QModelIndex &index, int role) const
{
    // TODO: Implement me!
    return QVariant();
}

void AccountsListModel::addAccount(Telepathy::Client::Account *account)
{
    kDebug() << "Creating a new AccountItem from account:" << account;
    // Check if the account is already in the model.
    bool found = false;

    foreach(const AccountItem* ai, m_unreadyAccounts)
    {
        if(ai->account() == account)
        {
            found = true;
            break;
        }
    }
    if(!found)
    {
        foreach(const AccountItem* ai, m_readyAccounts)
        {
            if(ai->account() == account)
            {
                found = true;
                break;
            }
        }
    }

    if(found)
    {
       kDebug() << "Requested to add account"
               << account
               << "to model, but it is already present. Doing nothing.";
   }
   else
   {
       AccountItem *item = new AccountItem(account, this);
       m_unreadyAccounts.append(item);
       connect(item, SIGNAL(ready()), this, SLOT(onAccountItemReady()));
       connect(item, SIGNAL(removed()), this, SLOT(onAccountItemRemoved()));
       connect(item, SIGNAL(updated()), this, SLOT(onAccountItemUpdated()));
   }
}

void AccountsListModel::onAccountItemReady()
{
    // TODO: Implement me!
}

void AccountsListModel::onAccountItemRemoved()
{
    // TODO: Implement me!
}

void AccountsListModel::onAccountItemUpdated()
{
    // TODO: Implement me!
}

#include "accounts-list-model.moc"

<commit_msg>Implement rowCount() and data() methods on the accountsList model.<commit_after>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * 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 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "accounts-list-model.h"

#include "account-item.h"

#include <kdebug.h>

#include <TelepathyQt4/Client/Account>

AccountsListModel::AccountsListModel(QObject *parent)
 : QAbstractListModel(parent)
{
    m_unreadyAccounts.clear();
    m_readyAccounts.clear();
}

AccountsListModel::~AccountsListModel()
{
    // TODO: Implement me!
}

int AccountsListModel::rowCount(const QModelIndex &index) const
{
    if(index == QModelIndex())
    {
       return m_readyAccounts.size();
    }

    return 0;
}

QVariant AccountsListModel::data(const QModelIndex &index, int role) const
{
    // FIXME: This is a basic implementation just so I can see what's going
    // on while developing this code further. Needs expanding.
    if(role == Qt::DisplayRole)
    {
        return QVariant(m_readyAccounts.at(index.row())->account()->displayName());
    }

    return QVariant();
}

void AccountsListModel::addAccount(Telepathy::Client::Account *account)
{
    kDebug() << "Creating a new AccountItem from account:" << account;
    // Check if the account is already in the model.
    bool found = false;

    foreach(const AccountItem* ai, m_unreadyAccounts)
    {
        if(ai->account() == account)
        {
            found = true;
            break;
        }
    }
    if(!found)
    {
        foreach(const AccountItem* ai, m_readyAccounts)
        {
            if(ai->account() == account)
            {
                found = true;
                break;
            }
        }
    }

    if(found)
    {
       kDebug() << "Requested to add account"
               << account
               << "to model, but it is already present. Doing nothing.";
   }
   else
   {
       AccountItem *item = new AccountItem(account, this);
       m_unreadyAccounts.append(item);
       connect(item, SIGNAL(ready()), this, SLOT(onAccountItemReady()));
       connect(item, SIGNAL(removed()), this, SLOT(onAccountItemRemoved()));
       connect(item, SIGNAL(updated()), this, SLOT(onAccountItemUpdated()));
   }
}

void AccountsListModel::onAccountItemReady()
{
    // TODO: Implement me!
}

void AccountsListModel::onAccountItemRemoved()
{
    // TODO: Implement me!
}

void AccountsListModel::onAccountItemUpdated()
{
    // TODO: Implement me!
}

#include "accounts-list-model.moc"

<|endoftext|>