<commit_before>// Ouzel by Elviss Strazdins

#include "core/Engine.hpp"
#include "scene/Animators.hpp"
#include "PerspectiveSample.hpp"
#include "MainMenu.hpp"

using namespace ouzel;
using namespace audio;
using namespace graphics;
using namespace input;
using namespace math;

namespace samples
{
    PerspectiveSample::PerspectiveSample():
        submix{*engine->getAudio()},
        listener{*engine->getAudio()},
        jumpSubmix{*engine->getAudio()},
        jumpVoice{*engine->getAudio(), engine->getCache().getSound("jump.wav")},
        jumpPanner{*engine->getAudio()},
        backButton{"button.png", "button_selected.png", "button_down.png", "", "Back", "Arial", 1.0F, blackColor, blackColor, blackColor},
        cursor{*engine->getInputManager()}
    {
        cursor.init(SystemCursor::cross);

        if (Mouse* mouse = engine->getInputManager()->getMouse())
            mouse->setCursor(&cursor);

        handler.keyboardHandler = [this](const KeyboardEvent& event) {
            if (event.type == Event::Type::keyboardKeyPress)
            {
                switch (event.key)
                {
                    case Keyboard::Key::up:
                        cameraRotation.x() -= tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::down:
                        cameraRotation.x() += tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::left:
                        cameraRotation.y() -= tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::right:
                        cameraRotation.y() += tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::escape:
                    case Keyboard::Key::menu:
                    case Keyboard::Key::back:
                        engine->getSceneManager().setScene(std::make_unique<MainMenu>());
                        return true;
                    case Keyboard::Key::tab:
                        jumpVoice.play();
                        break;
                    case Keyboard::Key::s:
                        engine->getGraphics()->saveScreenshot("test.png");
                        break;
                    default:
                        break;
                }

                if (cameraRotation.x() < -tau<float> / 6.0F) cameraRotation.x() = -tau<float> / 6.0F;
                if (cameraRotation.x() > tau<float> / 6.0F) cameraRotation.x() = tau<float> / 6.0F;

                cameraActor.setRotation(Vector<float, 3>{cameraRotation.x(), cameraRotation.y(), 0.0F});
            }
            else if (event.type == Event::Type::keyboardKeyRelease)
            {
                switch (event.key)
                {
                    case Keyboard::Key::escape:
                    case Keyboard::Key::menu:
                    case Keyboard::Key::back:
                        return true;
                    default:
                        break;
                }
            }

            return false;
        };

        handler.mouseHandler = [this](const ouzel::MouseEvent& event) {
            if (event.type == Event::Type::mouseMove &&
                event.mouse->isButtonDown(Mouse::Button::left))
            {
                cameraRotation.x() -= event.difference.y();
                cameraRotation.y() -= event.difference.x();

                if (cameraRotation.x() < -tau<float> / 6.0F) cameraRotation.x() = -tau<float> / 6.0F;
                if (cameraRotation.x() > tau<float> / 6.0F) cameraRotation.x() = tau<float> / 6.0F;

                cameraActor.setRotation(Vector<float, 3>{cameraRotation.x(), cameraRotation.y(), 0.0F});
            }

            return false;
        };

        handler.touchHandler = [this](const ouzel::TouchEvent& event) {
            if (event.touchpad->isScreen() &&
                event.type == Event::Type::touchMove)
            {
                cameraRotation.x() -= event.difference.y();
                cameraRotation.y() -= event.difference.x();

                if (cameraRotation.x() < -tau<float> / 6.0F) cameraRotation.x() = -tau<float> / 6.0F;
                if (cameraRotation.x() > tau<float> / 6.0F) cameraRotation.x() = tau<float> / 6.0F;

                cameraActor.setRotation(Vector<float, 3>{cameraRotation.x(), cameraRotation.y(), 0.0F});
            }

            return false;
        };

        handler.gamepadHandler = [](const GamepadEvent& event) {
            if (event.type == Event::Type::gamepadButtonChange)
            {
                if (event.pressed &&
                    event.button == Gamepad::Button::faceRight)
                    engine->getSceneManager().setScene(std::make_unique<MainMenu>());
            }

            return false;
        };

        handler.uiHandler = [this](const UIEvent& event) {
            if (event.type == Event::Type::actorClick)
            {
                if (event.actor == &backButton)
                    engine->getSceneManager().setScene(std::make_unique<MainMenu>());
            }

            return false;
        };

        engine->getEventDispatcher().addEventHandler(handler);

        camera.setClearColorBuffer(true);
        camera.setClearColor(math::Color{0, 0, 128});
        camera.setClearDepthBuffer(true);
        camera.setDepthTest(true);

        camera.setProjectionMode(scene::Camera::ProjectionMode::perspective);
        camera.setFarPlane(1000.0F);
        cameraActor.setPosition(Vector<float, 3>{0.0F, 0.0F, -400.0F});
        cameraActor.addComponent(camera);
        layer.addChild(cameraActor);
        addLayer(layer);

        // floor
        floorSprite.init("floor.jpg");
        floorSprite.getMaterial()->textures[0]->setMaxAnisotropy(4);

        floor.addComponent(floorSprite);
        layer.addChild(floor);
        floor.setPosition(Vector<float, 2>{0.0F, -50.0F});
        floor.setRotation(Vector<float, 3>{tau<float> / 4.04F, tau<float> / 8.0F, 0.0F});

        // character
        characterSprite.init("run.json");
        characterSprite.setAnimation("", true);
        characterSprite.play();
        characterSprite.getMaterial()->textures[0]->setMaxAnisotropy(4);
        characterSprite.getMaterial()->cullMode = graphics::CullMode::none;

        character.addComponent(characterSprite);
        layer.addChild(character);
        character.setPosition(Vector<float, 2>{10.0F, 0.0F});

        submix.setOutput(&engine->getAudio()->getMasterMix());

        cameraActor.addComponent(listener);
        listener.setMix(&submix);
        submix.setOutput(&engine->getAudio()->getMasterMix());

        jumpSubmix.setOutput(&submix);
        jumpVoice.setOutput(&jumpSubmix);
        jumpSubmix.addEffect(&jumpPanner);
        jumpPanner.setRolloffFactor(0.01F);
        character.addComponent(jumpPanner);

        rotate = std::make_unique<scene::Rotate>(10.0F, Vector<float, 3>{0.0F, tau<float>, 0.0F});
        character.addComponent(*rotate);
        rotate->start();

        boxModel.init(*engine->getCache().getStaticMeshData("cube.obj"));
        box.addComponent(boxModel);
        box.setPosition(Vector<float, 3>{-160.0F, 0.0F, -50.0F});
        layer.addChild(box);

        guiCamera.setScaleMode(scene::Camera::ScaleMode::showAll);
        guiCamera.setTargetContentSize(math::Size<float, 2>{800.0F, 600.0F});
        guiCameraActor.addComponent(guiCamera);
        guiLayer.addChild(guiCameraActor);
        addLayer(guiLayer);

        guiLayer.addChild(menu);

        backButton.setPosition(Vector<float, 2>{-200.0F, -200.0F});
        menu.addWidget(backButton);
    }
}
<commit_msg>Fix the expression that was meant to mean 90 degrees<commit_after>// Ouzel by Elviss Strazdins

#include "core/Engine.hpp"
#include "scene/Animators.hpp"
#include "PerspectiveSample.hpp"
#include "MainMenu.hpp"

using namespace ouzel;
using namespace audio;
using namespace graphics;
using namespace input;
using namespace math;

namespace samples
{
    PerspectiveSample::PerspectiveSample():
        submix{*engine->getAudio()},
        listener{*engine->getAudio()},
        jumpSubmix{*engine->getAudio()},
        jumpVoice{*engine->getAudio(), engine->getCache().getSound("jump.wav")},
        jumpPanner{*engine->getAudio()},
        backButton{"button.png", "button_selected.png", "button_down.png", "", "Back", "Arial", 1.0F, blackColor, blackColor, blackColor},
        cursor{*engine->getInputManager()}
    {
        cursor.init(SystemCursor::cross);

        if (Mouse* mouse = engine->getInputManager()->getMouse())
            mouse->setCursor(&cursor);

        handler.keyboardHandler = [this](const KeyboardEvent& event) {
            if (event.type == Event::Type::keyboardKeyPress)
            {
                switch (event.key)
                {
                    case Keyboard::Key::up:
                        cameraRotation.x() -= tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::down:
                        cameraRotation.x() += tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::left:
                        cameraRotation.y() -= tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::right:
                        cameraRotation.y() += tau<float> / 100.0F;
                        break;
                    case Keyboard::Key::escape:
                    case Keyboard::Key::menu:
                    case Keyboard::Key::back:
                        engine->getSceneManager().setScene(std::make_unique<MainMenu>());
                        return true;
                    case Keyboard::Key::tab:
                        jumpVoice.play();
                        break;
                    case Keyboard::Key::s:
                        engine->getGraphics()->saveScreenshot("test.png");
                        break;
                    default:
                        break;
                }

                if (cameraRotation.x() < -tau<float> / 6.0F) cameraRotation.x() = -tau<float> / 6.0F;
                if (cameraRotation.x() > tau<float> / 6.0F) cameraRotation.x() = tau<float> / 6.0F;

                cameraActor.setRotation(Vector<float, 3>{cameraRotation.x(), cameraRotation.y(), 0.0F});
            }
            else if (event.type == Event::Type::keyboardKeyRelease)
            {
                switch (event.key)
                {
                    case Keyboard::Key::escape:
                    case Keyboard::Key::menu:
                    case Keyboard::Key::back:
                        return true;
                    default:
                        break;
                }
            }

            return false;
        };

        handler.mouseHandler = [this](const ouzel::MouseEvent& event) {
            if (event.type == Event::Type::mouseMove &&
                event.mouse->isButtonDown(Mouse::Button::left))
            {
                cameraRotation.x() -= event.difference.y();
                cameraRotation.y() -= event.difference.x();

                if (cameraRotation.x() < -tau<float> / 6.0F) cameraRotation.x() = -tau<float> / 6.0F;
                if (cameraRotation.x() > tau<float> / 6.0F) cameraRotation.x() = tau<float> / 6.0F;

                cameraActor.setRotation(Vector<float, 3>{cameraRotation.x(), cameraRotation.y(), 0.0F});
            }

            return false;
        };

        handler.touchHandler = [this](const ouzel::TouchEvent& event) {
            if (event.touchpad->isScreen() &&
                event.type == Event::Type::touchMove)
            {
                cameraRotation.x() -= event.difference.y();
                cameraRotation.y() -= event.difference.x();

                if (cameraRotation.x() < -tau<float> / 6.0F) cameraRotation.x() = -tau<float> / 6.0F;
                if (cameraRotation.x() > tau<float> / 6.0F) cameraRotation.x() = tau<float> / 6.0F;

                cameraActor.setRotation(Vector<float, 3>{cameraRotation.x(), cameraRotation.y(), 0.0F});
            }

            return false;
        };

        handler.gamepadHandler = [](const GamepadEvent& event) {
            if (event.type == Event::Type::gamepadButtonChange)
            {
                if (event.pressed &&
                    event.button == Gamepad::Button::faceRight)
                    engine->getSceneManager().setScene(std::make_unique<MainMenu>());
            }

            return false;
        };

        handler.uiHandler = [this](const UIEvent& event) {
            if (event.type == Event::Type::actorClick)
            {
                if (event.actor == &backButton)
                    engine->getSceneManager().setScene(std::make_unique<MainMenu>());
            }

            return false;
        };

        engine->getEventDispatcher().addEventHandler(handler);

        camera.setClearColorBuffer(true);
        camera.setClearColor(math::Color{0, 0, 128});
        camera.setClearDepthBuffer(true);
        camera.setDepthTest(true);

        camera.setProjectionMode(scene::Camera::ProjectionMode::perspective);
        camera.setFarPlane(1000.0F);
        cameraActor.setPosition(Vector<float, 3>{0.0F, 0.0F, -400.0F});
        cameraActor.addComponent(camera);
        layer.addChild(cameraActor);
        addLayer(layer);

        // floor
        floorSprite.init("floor.jpg");
        floorSprite.getMaterial()->textures[0]->setMaxAnisotropy(4);

        floor.addComponent(floorSprite);
        layer.addChild(floor);
        floor.setPosition(Vector<float, 2>{0.0F, -50.0F});
        floor.setRotation(Vector<float, 3>{tau<float> / 4.0F, tau<float> / 8.0F, 0.0F});

        // character
        characterSprite.init("run.json");
        characterSprite.setAnimation("", true);
        characterSprite.play();
        characterSprite.getMaterial()->textures[0]->setMaxAnisotropy(4);
        characterSprite.getMaterial()->cullMode = graphics::CullMode::none;

        character.addComponent(characterSprite);
        layer.addChild(character);
        character.setPosition(Vector<float, 2>{10.0F, 0.0F});

        submix.setOutput(&engine->getAudio()->getMasterMix());

        cameraActor.addComponent(listener);
        listener.setMix(&submix);
        submix.setOutput(&engine->getAudio()->getMasterMix());

        jumpSubmix.setOutput(&submix);
        jumpVoice.setOutput(&jumpSubmix);
        jumpSubmix.addEffect(&jumpPanner);
        jumpPanner.setRolloffFactor(0.01F);
        character.addComponent(jumpPanner);

        rotate = std::make_unique<scene::Rotate>(10.0F, Vector<float, 3>{0.0F, tau<float>, 0.0F});
        character.addComponent(*rotate);
        rotate->start();

        boxModel.init(*engine->getCache().getStaticMeshData("cube.obj"));
        box.addComponent(boxModel);
        box.setPosition(Vector<float, 3>{-160.0F, 0.0F, -50.0F});
        layer.addChild(box);

        guiCamera.setScaleMode(scene::Camera::ScaleMode::showAll);
        guiCamera.setTargetContentSize(math::Size<float, 2>{800.0F, 600.0F});
        guiCameraActor.addComponent(guiCamera);
        guiLayer.addChild(guiCameraActor);
        addLayer(guiLayer);

        guiLayer.addChild(menu);

        backButton.setPosition(Vector<float, 2>{-200.0F, -200.0F});
        menu.addWidget(backButton);
    }
}
<|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/chrome_browser_main_android.h"

#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/path_service.h"
#include "cc/base/switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/breakpad/app/breakpad_linux.h"
#include "components/breakpad/browser/crash_dump_manager_android.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/common/main_function_params.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

ChromeBrowserMainPartsAndroid::ChromeBrowserMainPartsAndroid(
    const content::MainFunctionParams& parameters)
    : ChromeBrowserMainParts(parameters) {
}

ChromeBrowserMainPartsAndroid::~ChromeBrowserMainPartsAndroid() {
}

void ChromeBrowserMainPartsAndroid::PreProfileInit() {
  TRACE_EVENT0("startup", "ChromeBrowserMainPartsAndroid::PreProfileInit")
#if defined(GOOGLE_CHROME_BUILD)
  // TODO(jcivelli): we should not initialize the crash-reporter when it was not
  // enabled. Right now if it is disabled we still generate the minidumps but we
  // do not upload them.
  bool breakpad_enabled = true;
#else
  bool breakpad_enabled = false;
#endif

  // Allow Breakpad to be enabled in Chromium builds for testing purposes.
  if (!breakpad_enabled)
    breakpad_enabled = CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableCrashReporterForTesting);

  if (breakpad_enabled) {
    base::FilePath crash_dump_dir;
    PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dump_dir);
    crash_dump_manager_.reset(new breakpad::CrashDumpManager(crash_dump_dir));
  }

  ChromeBrowserMainParts::PreProfileInit();
}

void ChromeBrowserMainPartsAndroid::PreEarlyInitialization() {
  TRACE_EVENT0("startup",
    "ChromeBrowserMainPartsAndroid::PreEarlyInitialization")
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  content::Compositor::Initialize();

  // Chrome on Android does not use default MessageLoop. It has its own
  // Android specific MessageLoop.
  DCHECK(!main_message_loop_.get());

  // Create and start the MessageLoop.
  // This is a critical point in the startup process.
  {
    TRACE_EVENT0("startup",
      "ChromeBrowserMainPartsAndroid::PreEarlyInitialization:CreateUiMsgLoop");
    main_message_loop_.reset(new base::MessageLoopForUI);
  }

  {
    TRACE_EVENT0("startup",
      "ChromeBrowserMainPartsAndroid::PreEarlyInitialization:StartUiMsgLoop");
    base::MessageLoopForUI::current()->Start();
  }

  CommandLine::ForCurrentProcess()->AppendSwitch(
      cc::switches::kCompositeToMailbox);

  ChromeBrowserMainParts::PreEarlyInitialization();
}

void ChromeBrowserMainPartsAndroid::ShowMissingLocaleMessageBox() {
  NOTREACHED();
}
<commit_msg>Android: Remove leftover kCompositeToMailbox cmdline<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/chrome_browser_main_android.h"

#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/breakpad/app/breakpad_linux.h"
#include "components/breakpad/browser/crash_dump_manager_android.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/common/main_function_params.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

ChromeBrowserMainPartsAndroid::ChromeBrowserMainPartsAndroid(
    const content::MainFunctionParams& parameters)
    : ChromeBrowserMainParts(parameters) {
}

ChromeBrowserMainPartsAndroid::~ChromeBrowserMainPartsAndroid() {
}

void ChromeBrowserMainPartsAndroid::PreProfileInit() {
  TRACE_EVENT0("startup", "ChromeBrowserMainPartsAndroid::PreProfileInit")
#if defined(GOOGLE_CHROME_BUILD)
  // TODO(jcivelli): we should not initialize the crash-reporter when it was not
  // enabled. Right now if it is disabled we still generate the minidumps but we
  // do not upload them.
  bool breakpad_enabled = true;
#else
  bool breakpad_enabled = false;
#endif

  // Allow Breakpad to be enabled in Chromium builds for testing purposes.
  if (!breakpad_enabled)
    breakpad_enabled = CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableCrashReporterForTesting);

  if (breakpad_enabled) {
    base::FilePath crash_dump_dir;
    PathService::Get(chrome::DIR_CRASH_DUMPS, &crash_dump_dir);
    crash_dump_manager_.reset(new breakpad::CrashDumpManager(crash_dump_dir));
  }

  ChromeBrowserMainParts::PreProfileInit();
}

void ChromeBrowserMainPartsAndroid::PreEarlyInitialization() {
  TRACE_EVENT0("startup",
    "ChromeBrowserMainPartsAndroid::PreEarlyInitialization")
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  content::Compositor::Initialize();

  // Chrome on Android does not use default MessageLoop. It has its own
  // Android specific MessageLoop.
  DCHECK(!main_message_loop_.get());

  // Create and start the MessageLoop.
  // This is a critical point in the startup process.
  {
    TRACE_EVENT0("startup",
      "ChromeBrowserMainPartsAndroid::PreEarlyInitialization:CreateUiMsgLoop");
    main_message_loop_.reset(new base::MessageLoopForUI);
  }

  {
    TRACE_EVENT0("startup",
      "ChromeBrowserMainPartsAndroid::PreEarlyInitialization:StartUiMsgLoop");
    base::MessageLoopForUI::current()->Start();
  }

  ChromeBrowserMainParts::PreEarlyInitialization();
}

void ChromeBrowserMainPartsAndroid::ShowMissingLocaleMessageBox() {
  NOTREACHED();
}
<|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 "base/command_line.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_init.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "testing/gtest/include/gtest/gtest.h"

class BrowserInitTest : public ExtensionBrowserTest {
 protected:
  // Helper functions return void so that we can ASSERT*().
  // Use ASSERT_NO_FATAL_FAILURE around calls to these functions to stop the
  // test if an assert fails.
  void LoadApp(const std::string& app_name,
               const Extension** out_app_extension) {
    ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(app_name.c_str())));

    ExtensionService* service = browser()->profile()->GetExtensionService();
    *out_app_extension = service->GetExtensionById(
        last_loaded_extension_id_, false);
    ASSERT_TRUE(*out_app_extension);

    // Code that opens a new browser assumes we start with exactly one.
    ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
  }

  void SetAppLaunchPref(const std::string& app_id,
                        ExtensionPrefs::LaunchType launch_type) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    service->extension_prefs()->SetLaunchType(app_id, launch_type);
  }

  // Check that there are two browsers.  Find the one that is not |browser()|.
  void FindOneOtherBrowser(Browser** out_other_browser) {
    // There should only be one other browser.
    ASSERT_EQ(2u, BrowserList::GetBrowserCount(browser()->profile()));

    // Find the new browser.
    Browser* other_browser = NULL;
    for (BrowserList::const_iterator i = BrowserList::begin();
         i != BrowserList::end() && !other_browser; ++i) {
      if (*i != browser())
        other_browser = *i;
    }
    ASSERT_TRUE(other_browser);
    ASSERT_TRUE(other_browser != browser());
    *out_other_browser = other_browser;
  }
};

class OpenURLsPopupObserver : public BrowserList::Observer {
 public:
  OpenURLsPopupObserver() : added_browser_(NULL) { }

  virtual void OnBrowserAdded(const Browser* browser) {
    added_browser_ = browser;
  }

  virtual void OnBrowserRemoved(const Browser* browser) { }

  const Browser* added_browser_;
};

// Test that when there is a popup as the active browser any requests to
// BrowserInit::LaunchWithProfile::OpenURLsInBrowser don't crash because
// there's no explicit profile given.
IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenURLsPopup) {
  std::vector<GURL> urls;
  urls.push_back(GURL("http://localhost"));

  // Note that in our testing we do not ever query the BrowserList for the "last
  // active" browser. That's because the browsers are set as "active" by
  // platform UI toolkit messages, and those messages are not sent during unit
  // testing sessions.

  OpenURLsPopupObserver observer;
  BrowserList::AddObserver(&observer);

  Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP,
                                          browser()->profile());
  ASSERT_TRUE(popup->is_type_popup());
  ASSERT_EQ(popup, observer.added_browser_);

  CommandLine dummy(CommandLine::NO_PROGRAM);
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
  // This should create a new window, but re-use the profile from |popup|. If
  // it used a NULL or invalid profile, it would crash.
  launch.OpenURLsInBrowser(popup, false, urls);
  ASSERT_NE(popup, observer.added_browser_);
  BrowserList::RemoveObserver(&observer);
}

// Verify that startup URLs are honored when the process already exists but has
// no tabbed browser windows (eg. as if the process is running only due to a
// background application.
IN_PROC_BROWSER_TEST_F(BrowserInitTest,
                       StartupURLsOnNewWindowWithNoTabbedBrowsers) {
  // Use a couple arbitrary URLs.
  std::vector<GURL> urls;
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title2.html"))));

  // Set the startup preference to open these URLs.
  SessionStartupPref pref(SessionStartupPref::URLS);
  pref.urls = urls;
  SessionStartupPref::SetStartupPref(browser()->profile(), pref);

  // Close the browser.
  browser()->window()->Close();

  // Do a simple non-process-startup browser launch.
  CommandLine dummy(CommandLine::NO_PROGRAM);
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // This should have created a new browser window.  |browser()| is still
  // around at this point, even though we've closed it's window.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // The new browser should have one tab for each URL.
  ASSERT_EQ(static_cast<int>(urls.size()), new_browser->tab_count());
  for (size_t i=0; i < urls.size(); i++) {
    EXPECT_EQ(urls[i], new_browser->GetTabContentsAt(i)->GetURL());
  }
}

// Verify that startup URLs aren't used when the process already exists
// and has other tabbed browser windows.  This is the common case of starting a
// new browser.
IN_PROC_BROWSER_TEST_F(BrowserInitTest,
                       StartupURLsOnNewWindow) {
  // Use a couple arbitrary URLs.
  std::vector<GURL> urls;
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title2.html"))));

  // Set the startup preference to open these URLs.
  SessionStartupPref pref(SessionStartupPref::URLS);
  pref.urls = urls;
  SessionStartupPref::SetStartupPref(browser()->profile(), pref);

  // Do a simple non-process-startup browser launch.
  CommandLine dummy(CommandLine::NO_PROGRAM);
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // This should have created a new browser window.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // The new browser should have exactly one tab (not the startup URLs).
  ASSERT_EQ(1, new_browser->tab_count());
}

// App shortcuts are not implemented on mac os.
#if !defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutNoPref) {
  // Load an app with launch.container = 'tab'.
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));

  // Add --app-id=<extension->id()> to the command line.
  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());

  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // No pref was set, so the app should have opened in a window.
  // The launch should have created a new browser.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // Expect an app window.
  EXPECT_TRUE(new_browser->is_app());

  // The browser's app_name should include the app's ID.
  EXPECT_NE(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutWindowPref) {
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));

  // Set a pref indicating that the user wants to open this app in a window.
  SetAppLaunchPref(extension_app->id(), ExtensionPrefs::LAUNCH_WINDOW);

  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // Pref was set to open in a window, so the app should have opened in a
  // window.  The launch should have created a new browser. Find the new
  // browser.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // Expect an app window.
  EXPECT_TRUE(new_browser->is_app());

  // The browser's app_name should include the app's ID.
  EXPECT_NE(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutTabPref) {
  // Load an app with launch.container = 'tab'.
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));

  // Set a pref indicating that the user wants to open this app in a window.
  SetAppLaunchPref(extension_app->id(), ExtensionPrefs::LAUNCH_REGULAR);

  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // When an app shortcut is open and the pref indicates a tab should
  // open, the tab is open in a new browser window.  Expect a new window.
  ASSERT_EQ(2u, BrowserList::GetBrowserCount(browser()->profile()));

  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // The tab should be in a tabbed window.
  EXPECT_TRUE(new_browser->is_type_tabbed());

  // The browser's app_name should not include the app's ID: It is in a
  // normal browser.
  EXPECT_EQ(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutPanel) {
  // Load an app with launch.container = 'panel'.
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_panel_container", &extension_app));

  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // The launch should have created a new browser, with a panel type.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // Expect an app panel.
  EXPECT_TRUE(new_browser->is_type_panel() && new_browser->is_app());

  // The new browser's app_name should include the app's ID.
  EXPECT_NE(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

#endif  // !defined(OS_MACOSX)
<commit_msg>Disable StartupURLsOnNewWindowWithNoTabbedBrowsers on aura<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 "base/command_line.h"
#include "base/file_path.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_init.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "testing/gtest/include/gtest/gtest.h"

class BrowserInitTest : public ExtensionBrowserTest {
 protected:
  // Helper functions return void so that we can ASSERT*().
  // Use ASSERT_NO_FATAL_FAILURE around calls to these functions to stop the
  // test if an assert fails.
  void LoadApp(const std::string& app_name,
               const Extension** out_app_extension) {
    ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(app_name.c_str())));

    ExtensionService* service = browser()->profile()->GetExtensionService();
    *out_app_extension = service->GetExtensionById(
        last_loaded_extension_id_, false);
    ASSERT_TRUE(*out_app_extension);

    // Code that opens a new browser assumes we start with exactly one.
    ASSERT_EQ(1u, BrowserList::GetBrowserCount(browser()->profile()));
  }

  void SetAppLaunchPref(const std::string& app_id,
                        ExtensionPrefs::LaunchType launch_type) {
    ExtensionService* service = browser()->profile()->GetExtensionService();
    service->extension_prefs()->SetLaunchType(app_id, launch_type);
  }

  // Check that there are two browsers.  Find the one that is not |browser()|.
  void FindOneOtherBrowser(Browser** out_other_browser) {
    // There should only be one other browser.
    ASSERT_EQ(2u, BrowserList::GetBrowserCount(browser()->profile()));

    // Find the new browser.
    Browser* other_browser = NULL;
    for (BrowserList::const_iterator i = BrowserList::begin();
         i != BrowserList::end() && !other_browser; ++i) {
      if (*i != browser())
        other_browser = *i;
    }
    ASSERT_TRUE(other_browser);
    ASSERT_TRUE(other_browser != browser());
    *out_other_browser = other_browser;
  }
};

class OpenURLsPopupObserver : public BrowserList::Observer {
 public:
  OpenURLsPopupObserver() : added_browser_(NULL) { }

  virtual void OnBrowserAdded(const Browser* browser) {
    added_browser_ = browser;
  }

  virtual void OnBrowserRemoved(const Browser* browser) { }

  const Browser* added_browser_;
};

// Test that when there is a popup as the active browser any requests to
// BrowserInit::LaunchWithProfile::OpenURLsInBrowser don't crash because
// there's no explicit profile given.
IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenURLsPopup) {
  std::vector<GURL> urls;
  urls.push_back(GURL("http://localhost"));

  // Note that in our testing we do not ever query the BrowserList for the "last
  // active" browser. That's because the browsers are set as "active" by
  // platform UI toolkit messages, and those messages are not sent during unit
  // testing sessions.

  OpenURLsPopupObserver observer;
  BrowserList::AddObserver(&observer);

  Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP,
                                          browser()->profile());
  ASSERT_TRUE(popup->is_type_popup());
  ASSERT_EQ(popup, observer.added_browser_);

  CommandLine dummy(CommandLine::NO_PROGRAM);
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
  // This should create a new window, but re-use the profile from |popup|. If
  // it used a NULL or invalid profile, it would crash.
  launch.OpenURLsInBrowser(popup, false, urls);
  ASSERT_NE(popup, observer.added_browser_);
  BrowserList::RemoveObserver(&observer);
}

#if defined(USE_AURA)
// Fails on aura. See crbug.com/106248.
#define MAYBE_StartupURLsOnNewWindowWithNoTabbedBrowsers DISABLED_StartupURLsOnNewWindowWithNoTabbedBrowsers
#else
#define MAYBE_StartupURLsOnNewWindowWithNoTabbedBrowsers StartupURLsOnNewWindowWithNoTabbedBrowsers
#endif

// Verify that startup URLs are honored when the process already exists but has
// no tabbed browser windows (eg. as if the process is running only due to a
// background application.
IN_PROC_BROWSER_TEST_F(BrowserInitTest,
                       MAYBE_StartupURLsOnNewWindowWithNoTabbedBrowsers) {
  // Use a couple arbitrary URLs.
  std::vector<GURL> urls;
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title2.html"))));

  // Set the startup preference to open these URLs.
  SessionStartupPref pref(SessionStartupPref::URLS);
  pref.urls = urls;
  SessionStartupPref::SetStartupPref(browser()->profile(), pref);

  // Close the browser.
  browser()->window()->Close();

  // Do a simple non-process-startup browser launch.
  CommandLine dummy(CommandLine::NO_PROGRAM);
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // This should have created a new browser window.  |browser()| is still
  // around at this point, even though we've closed it's window.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // The new browser should have one tab for each URL.
  ASSERT_EQ(static_cast<int>(urls.size()), new_browser->tab_count());
  for (size_t i=0; i < urls.size(); i++) {
    EXPECT_EQ(urls[i], new_browser->GetTabContentsAt(i)->GetURL());
  }
}

// Verify that startup URLs aren't used when the process already exists
// and has other tabbed browser windows.  This is the common case of starting a
// new browser.
IN_PROC_BROWSER_TEST_F(BrowserInitTest,
                       StartupURLsOnNewWindow) {
  // Use a couple arbitrary URLs.
  std::vector<GURL> urls;
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title1.html"))));
  urls.push_back(ui_test_utils::GetTestUrl(
      FilePath(FilePath::kCurrentDirectory),
      FilePath(FILE_PATH_LITERAL("title2.html"))));

  // Set the startup preference to open these URLs.
  SessionStartupPref pref(SessionStartupPref::URLS);
  pref.urls = urls;
  SessionStartupPref::SetStartupPref(browser()->profile(), pref);

  // Do a simple non-process-startup browser launch.
  CommandLine dummy(CommandLine::NO_PROGRAM);
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // This should have created a new browser window.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // The new browser should have exactly one tab (not the startup URLs).
  ASSERT_EQ(1, new_browser->tab_count());
}

// App shortcuts are not implemented on mac os.
#if !defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutNoPref) {
  // Load an app with launch.container = 'tab'.
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));

  // Add --app-id=<extension->id()> to the command line.
  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());

  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // No pref was set, so the app should have opened in a window.
  // The launch should have created a new browser.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // Expect an app window.
  EXPECT_TRUE(new_browser->is_app());

  // The browser's app_name should include the app's ID.
  EXPECT_NE(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutWindowPref) {
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));

  // Set a pref indicating that the user wants to open this app in a window.
  SetAppLaunchPref(extension_app->id(), ExtensionPrefs::LAUNCH_WINDOW);

  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // Pref was set to open in a window, so the app should have opened in a
  // window.  The launch should have created a new browser. Find the new
  // browser.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // Expect an app window.
  EXPECT_TRUE(new_browser->is_app());

  // The browser's app_name should include the app's ID.
  EXPECT_NE(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutTabPref) {
  // Load an app with launch.container = 'tab'.
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_tab_container", &extension_app));

  // Set a pref indicating that the user wants to open this app in a window.
  SetAppLaunchPref(extension_app->id(), ExtensionPrefs::LAUNCH_REGULAR);

  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // When an app shortcut is open and the pref indicates a tab should
  // open, the tab is open in a new browser window.  Expect a new window.
  ASSERT_EQ(2u, BrowserList::GetBrowserCount(browser()->profile()));

  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // The tab should be in a tabbed window.
  EXPECT_TRUE(new_browser->is_type_tabbed());

  // The browser's app_name should not include the app's ID: It is in a
  // normal browser.
  EXPECT_EQ(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

IN_PROC_BROWSER_TEST_F(BrowserInitTest, OpenAppShortcutPanel) {
  // Load an app with launch.container = 'panel'.
  const Extension* extension_app = NULL;
  ASSERT_NO_FATAL_FAILURE(LoadApp("app_with_panel_container", &extension_app));

  CommandLine command_line(CommandLine::NO_PROGRAM);
  command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
  BrowserInit::IsFirstRun first_run = FirstRun::IsChromeFirstRun() ?
      BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
  BrowserInit::LaunchWithProfile launch(FilePath(), command_line, first_run);
  ASSERT_TRUE(launch.Launch(browser()->profile(), std::vector<GURL>(), false));

  // The launch should have created a new browser, with a panel type.
  Browser* new_browser = NULL;
  ASSERT_NO_FATAL_FAILURE(FindOneOtherBrowser(&new_browser));

  // Expect an app panel.
  EXPECT_TRUE(new_browser->is_type_panel() && new_browser->is_app());

  // The new browser's app_name should include the app's ID.
  EXPECT_NE(
      new_browser->app_name_.find(extension_app->id()),
      std::string::npos) << new_browser->app_name_;
}

#endif  // !defined(OS_MACOSX)
<|endoftext|>


<commit_before>//All functions in this file are meant to be hook helpers for psi_field.h.
//Do NOT modify any functions in this file!

#include "psi_field.h"
#include "../SCBW/scbwdata.h"
#include "../hook_tools.h"

//-------- Unit selection hooks --------//

void showAllPsiFields() {
  const u32 Func_showAllPsiFields = 0x00493640;

  __asm {
    PUSHAD
    CALL Func_showAllPsiFields
    POPAD
  }
}

void hideAllPsiFields() {
  const u32 Func_hideAllPsiFields = 0x00494100;

  __asm {
    PUSHAD
    CALL Func_hideAllPsiFields
    POPAD
  }
}

//If @p unit is a psi provider, make all psi field graphics visible.
void showAllPsiFieldsOnSelect(CUnit *unit) {
  if (!(*IS_IN_REPLAY) && unit->playerId == (*LOCAL_NATION_ID)) {
    if ((unit->status & UnitStatus::Completed) && hooks::isReadyToMakePsiField(unit)) {
       showAllPsiFields();
    }
  }
}

//If @p unit is a psi provider, make all psi field graphics invisible.
void hideAllPsiFieldsOnUnselect(CUnit *unit) {
  if (!(*IS_IN_REPLAY) && unit->playerId == (*LOCAL_NATION_ID)) {
    if ((unit->status & UnitStatus::Completed) && hooks::isReadyToMakePsiField(unit)) {
       hideAllPsiFields();
    }
  }
}

void __declspec(naked) showAllPsiFieldsOnSelectWrapper() {
  static CUnit *unit;
  __asm {
    PUSHAD
    MOV unit, EDI
  }

  showAllPsiFieldsOnSelect(unit);

  __asm {
    POPAD
    POP EDI
    POP ESI
    POP EBX
    MOV ESP, EBP
    POP EBP
    RETN 4
  }
}

void __declspec(naked) hideAllPsiFieldsOnUnselectWrapper() {
  static CUnit *unit;
  __asm {
    POP EDI   ;//Clean up part of the stack
    PUSHAD
    MOV unit, ESI
  }

  hideAllPsiFieldsOnUnselect(unit);

  __asm {
    POPAD
    POP ESI
    RETN
  }
}

//-------- Save & load game hooks --------//

const u32 packUnitData_PsiProvider_Return = 0x004E3961;
void __declspec(naked) packUnitData_PsiProvider() {
  CUnit *unit; u16 unitId;

  __asm {
    PUSHAD
    MOV EBP, ESP
    MOV unitId, CX
    MOV unit, ESI
  }

  if (hooks::canMakePsiField(unitId)) {
    const CSprite *psiFieldSprite = unit->building.pylonAura;
    if (psiFieldSprite)
      *(u32*)&unit->building.pylonAura = (psiFieldSprite - spriteTable) / sizeof(CSprite) + 1;
  }

  __asm {
    POPAD
    JMP packUnitData_PsiProvider_Return
  }
}

const u32 unpackUnitData_PsiProvider_Return = 0x004E31A3;
void __declspec(naked) unpackUnitData_PsiProvider() {
  CUnit *unit; u16 unitId;

  __asm {
    PUSHAD
    MOV EBP, ESP
    MOV unitId, CX
    MOV unit, ESI
  }

  if (hooks::canMakePsiField(unitId))
    if (unit->building.pylonAura != 0)
      unit->building.pylonAura = &spriteTable[(int)unit->building.pylonAura];

  __asm {
    POPAD
    JMP unpackUnitData_PsiProvider_Return
  }
}

//-------- Hook injector --------//
namespace hooks {

void injectPsiFieldHooks() {
  jmpPatch(showAllPsiFieldsOnSelectWrapper,   0x004E6224);
  jmpPatch(hideAllPsiFieldsOnUnselectWrapper, 0x004E62BE);
  jmpPatch(packUnitData_PsiProvider,          0x004E3935);
  jmpPatch(unpackUnitData_PsiProvider,        0x004E3182);
}

} //hooks
<commit_msg>GPTP: Fixed a bug that caused Psi Field hooks to crash when attempting to save / load games.<commit_after>//All functions in this file are meant to be hook helpers for psi_field.h.
//Do NOT modify any functions in this file!

#include "psi_field.h"
#include "../SCBW/scbwdata.h"
#include "../hook_tools.h"

//-------- Unit selection hooks --------//

void showAllPsiFields() {
  const u32 Func_showAllPsiFields = 0x00493640;

  __asm {
    PUSHAD
    CALL Func_showAllPsiFields
    POPAD
  }
}

void hideAllPsiFields() {
  const u32 Func_hideAllPsiFields = 0x00494100;

  __asm {
    PUSHAD
    CALL Func_hideAllPsiFields
    POPAD
  }
}

//If @p unit is a psi provider, make all psi field graphics visible.
void showAllPsiFieldsOnSelect(CUnit *unit) {
  if (!(*IS_IN_REPLAY) && unit->playerId == (*LOCAL_NATION_ID)) {
    if ((unit->status & UnitStatus::Completed) && hooks::isReadyToMakePsiField(unit)) {
       showAllPsiFields();
    }
  }
}

//If @p unit is a psi provider, make all psi field graphics invisible.
void hideAllPsiFieldsOnUnselect(CUnit *unit) {
  if (!(*IS_IN_REPLAY) && unit->playerId == (*LOCAL_NATION_ID)) {
    if ((unit->status & UnitStatus::Completed) && hooks::isReadyToMakePsiField(unit)) {
       hideAllPsiFields();
    }
  }
}

void __declspec(naked) showAllPsiFieldsOnSelectWrapper() {
  static CUnit *unit;
  __asm {
    PUSHAD
    MOV unit, EDI
  }

  showAllPsiFieldsOnSelect(unit);

  __asm {
    POPAD
    POP EDI
    POP ESI
    POP EBX
    MOV ESP, EBP
    POP EBP
    RETN 4
  }
}

void __declspec(naked) hideAllPsiFieldsOnUnselectWrapper() {
  static CUnit *unit;
  __asm {
    POP EDI   ;//Clean up part of the stack
    PUSHAD
    MOV unit, ESI
  }

  hideAllPsiFieldsOnUnselect(unit);

  __asm {
    POPAD
    POP ESI
    RETN
  }
}

//-------- Save & load game hooks --------//

const u32 packUnitData_PsiProvider_Return = 0x004E3961;
void __declspec(naked) packUnitData_PsiProvider() {
  static CUnit *unit; u16 unitId;

  __asm {
    PUSHAD
    MOV EBP, ESP
    MOV unitId, CX
    MOV unit, ESI
  }

  if (hooks::canMakePsiField(unitId)) {
    if (unit->building.pylonAura)
      *(u32*)&unit->building.pylonAura = (unit->building.pylonAura - spriteTable) / sizeof(CSprite) + 1;
  }

  __asm {
    POPAD
    JMP packUnitData_PsiProvider_Return
  }
}

const u32 unpackUnitData_PsiProvider_Return = 0x004E31A3;
void __declspec(naked) unpackUnitData_PsiProvider() {
  static CUnit *unit; u16 unitId;

  __asm {
    PUSHAD
    MOV EBP, ESP
    MOV unitId, CX
    MOV unit, ESI
  }

  if (hooks::canMakePsiField(unitId))
    if (unit->building.pylonAura != 0)
      unit->building.pylonAura = &spriteTable[(int)unit->building.pylonAura];

  __asm {
    POPAD
    JMP unpackUnitData_PsiProvider_Return
  }
}

//-------- Hook injector --------//
namespace hooks {

void injectPsiFieldHooks() {
  jmpPatch(showAllPsiFieldsOnSelectWrapper,   0x004E6224);
  jmpPatch(hideAllPsiFieldsOnUnselectWrapper, 0x004E62BE);
  jmpPatch(packUnitData_PsiProvider,          0x004E3935);
  jmpPatch(unpackUnitData_PsiProvider,        0x004E3182);
}

} //hooks
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "vbalistbox.hxx"
#include "vbanewfont.hxx"
#include <comphelper/anytostring.hxx>
#include <com/sun/star/script/ArrayWrapper.hpp>
#include <com/sun/star/form/validation/XValidatableFormComponent.hpp>
#include <ooo/vba/msforms/fmMultiSelect.hpp>

using namespace com::sun::star;
using namespace ooo::vba;

const static OUString TEXT( "Text" );
const static OUString SELECTEDITEMS( "SelectedItems" );
const static OUString ITEMS( "StringItemList" );

ScVbaListBox::ScVbaListBox( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< css::uno::XInterface >& xControl, const uno::Reference< frame::XModel >& xModel, AbstractGeometryAttributes* pGeomHelper ) : ListBoxImpl_BASE( xParent, xContext, xControl, xModel, pGeomHelper )
{
    mpListHelper.reset( new ListControlHelper( m_xProps ) );
}

// Attributes
void SAL_CALL
ScVbaListBox::setListIndex( const uno::Any& _value ) throw (uno::RuntimeException)
{
    sal_Int32 nIndex = 0;
    _value >>= nIndex;
    uno::Reference< XPropValue > xPropVal( Selected( nIndex ), uno::UNO_QUERY_THROW );
    xPropVal->setValue( uno::makeAny( sal_True ) );
}

uno::Any SAL_CALL
ScVbaListBox::getListIndex() throw (uno::RuntimeException)
{
    uno::Sequence< sal_Int16 > sSelection;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= sSelection;
    if ( sSelection.getLength() == 0 )
        return uno::Any( sal_Int32( -1 ) );
    return uno::Any( sSelection[ 0 ] );
}

uno::Any SAL_CALL
ScVbaListBox::getValue() throw (uno::RuntimeException)
{
    uno::Sequence< sal_Int16 > sSelection;
    uno::Sequence< OUString > sItems;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= sSelection;
    m_xProps->getPropertyValue( ITEMS ) >>= sItems;
    if( getMultiSelect() )
        throw uno::RuntimeException( "Attribute use invalid." , uno::Reference< uno::XInterface >() );
    uno::Any aRet;
    if ( sSelection.getLength() )
        aRet = uno::makeAny( sItems[ sSelection[ 0 ] ] );
    return aRet;
}

void SAL_CALL
ScVbaListBox::setValue( const uno::Any& _value ) throw (uno::RuntimeException)
{
    if( getMultiSelect() )
    {
        throw uno::RuntimeException( "Attribute use invalid." , uno::Reference< uno::XInterface >() );
    }
    OUString sValue = getAnyAsString( _value );
    uno::Sequence< OUString > sList;
    m_xProps->getPropertyValue( ITEMS ) >>= sList;
    uno::Sequence< sal_Int16 > nList;
    sal_Int16 nLength = static_cast<sal_Int16>( sList.getLength() );
    sal_Int16 nValue = -1;
    sal_Int16 i = 0;
    for( i = 0; i < nLength; i++ )
    {
        if( sList[i].equals( sValue ) )
        {
            nValue = i;
            break;
        }
    }
    if( nValue == -1 )
        throw uno::RuntimeException( "Attribute use invalid." , uno::Reference< uno::XInterface >() );

    uno::Sequence< sal_Int16 > nSelectedIndices(1);
    uno::Sequence< sal_Int16 > nOldSelectedIndices;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= nOldSelectedIndices;
    nSelectedIndices[ 0 ] = nValue;
    m_xProps->setPropertyValue( SELECTEDITEMS, uno::makeAny( nSelectedIndices ) );
    if ( nSelectedIndices != nOldSelectedIndices )
        fireClickEvent();
    m_xProps->setPropertyValue( TEXT, uno::makeAny( sValue ) );
}

OUString SAL_CALL
ScVbaListBox::getText() throw (uno::RuntimeException)
{
    OUString result;
    getValue() >>= result;
    return result;
}

void SAL_CALL
ScVbaListBox::setText( const OUString& _text ) throw (uno::RuntimeException)
{
    setValue( uno::makeAny( _text ) ); // seems the same
}

sal_Int32 SAL_CALL
ScVbaListBox::getMultiSelect() throw (css::uno::RuntimeException)
{
    sal_Bool bMultiSelect = sal_False;
    m_xProps->getPropertyValue( "MultiSelection" ) >>= bMultiSelect;

    return bMultiSelect ? msforms::fmMultiSelect::fmMultiSelectMulti : msforms::fmMultiSelect::fmMultiSelectSingle;
}

void SAL_CALL
ScVbaListBox::setMultiSelect( sal_Int32 _multiselect ) throw (css::uno::RuntimeException)
{
    sal_Bool bBoolVal = false;
    switch ( _multiselect )
    {
        case  msforms::fmMultiSelect::fmMultiSelectMulti:
        case  msforms::fmMultiSelect::fmMultiSelectExtended:
            bBoolVal = sal_True;
            break;
        case msforms::fmMultiSelect::fmMultiSelectSingle:
            bBoolVal = sal_True;
            break;
        default:
            throw lang::IllegalArgumentException();
            break;
    }
    m_xProps->setPropertyValue( "MultiSelection" , uno::makeAny( bBoolVal ) );
}

css::uno::Any SAL_CALL
ScVbaListBox::Selected( sal_Int32 index ) throw (css::uno::RuntimeException)
{
    uno::Sequence< OUString > sList;
    m_xProps->getPropertyValue( ITEMS ) >>= sList;
    sal_Int16 nLength = static_cast< sal_Int16 >( sList.getLength() );
    // no choice but to do a horror cast as internally
    // the indices are but sal_Int16
    sal_Int16 nIndex = static_cast< sal_Int16 >( index );
    if( nIndex < 0 || nIndex >= nLength )
        throw uno::RuntimeException( "Error Number." , uno::Reference< uno::XInterface >() );
    m_nIndex = nIndex;
    return uno::makeAny( uno::Reference< XPropValue > ( new ScVbaPropValue( this ) ) );
}

// Methods
void SAL_CALL
ScVbaListBox::AddItem( const uno::Any& pvargItem, const uno::Any& pvargIndex ) throw (uno::RuntimeException)
{
    mpListHelper->AddItem( pvargItem, pvargIndex );
        }

void SAL_CALL
ScVbaListBox::removeItem( const uno::Any& index ) throw (uno::RuntimeException)
{
    mpListHelper->removeItem( index );
}

void SAL_CALL
ScVbaListBox::Clear(  ) throw (uno::RuntimeException)
{
    mpListHelper->Clear();
}

// this is called when something like the following vba code is used
// to set the selected state of particular entries in the Listbox
// ListBox1.Selected( 3 ) = false
//PropListener
void
ScVbaListBox::setValueEvent( const uno::Any& value )
{
    sal_Bool bValue = sal_False;
    if( !(value >>= bValue) )
        throw uno::RuntimeException( "Invalid type\n. need boolean." , uno::Reference< uno::XInterface >() );
    uno::Sequence< sal_Int16 > nList;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= nList;
    sal_Int16 nLength = static_cast<sal_Int16>( nList.getLength() );
    sal_Int16 nIndex = m_nIndex;
    for( sal_Int16 i = 0; i < nLength; i++ )
    {
        if( nList[i] == nIndex )
        {
            if( bValue )
                return;
            else
            {
                for( ; i < nLength - 1; i++ )
                {
                    nList[i] = nList[i + 1];
                }
                nList.realloc( nLength - 1 );
                //m_xProps->setPropertyValue( sSourceName, uno::makeAny( nList ) );
                fireClickEvent();
        m_xProps->setPropertyValue( SELECTEDITEMS, uno::makeAny( nList ) );
                return;
            }
        }
    }
    if( bValue )
    {
        if( getMultiSelect() )
        {
            nList.realloc( nLength + 1 );
            nList[nLength] = nIndex;
        }
        else
        {
            nList.realloc( 1 );
            nList[0] = nIndex;
        }
        //m_xProps->setPropertyValue( sSourceName, uno::makeAny( nList ) );
        fireClickEvent();
        m_xProps->setPropertyValue( SELECTEDITEMS, uno::makeAny( nList ) );
    }
}

// this is called when something like the following vba code is used
// to determine the selected state of particular entries in the Listbox
// msgbox ListBox1.Selected( 3 )

css::uno::Any
ScVbaListBox::getValueEvent()
{
    uno::Sequence< sal_Int16 > nList;
    m_xProps->getPropertyValue( "SelectedItems" ) >>= nList;
    sal_Int32 nLength = nList.getLength();
    sal_Int32 nIndex = m_nIndex;

    for( sal_Int32 i = 0; i < nLength; i++ )
    {
        if( nList[i] == nIndex )
            return uno::makeAny( sal_True );
    }

    return uno::makeAny( sal_False );
}

void SAL_CALL
ScVbaListBox::setRowSource( const OUString& _rowsource ) throw (uno::RuntimeException)
{
    ScVbaControl::setRowSource( _rowsource );
    mpListHelper->setRowSource( _rowsource );
}

sal_Int32 SAL_CALL
ScVbaListBox::getListCount() throw (uno::RuntimeException)
{
    return mpListHelper->getListCount();
}

uno::Any SAL_CALL
ScVbaListBox::List( const ::uno::Any& pvargIndex, const uno::Any& pvarColumn ) throw (uno::RuntimeException)
{
    return mpListHelper->List( pvargIndex, pvarColumn );
}

uno::Reference< msforms::XNewFont > SAL_CALL ScVbaListBox::getFont() throw (uno::RuntimeException)
{
    return new VbaNewFont( this, mxContext, m_xProps );
}

OUString
ScVbaListBox::getServiceImplName()
{
    return OUString("ScVbaListBox");
}

uno::Sequence< OUString >
ScVbaListBox::getServiceNames()
{
    static uno::Sequence< OUString > aServiceNames;
    if ( aServiceNames.getLength() == 0 )
    {
        aServiceNames.realloc( 1 );
        aServiceNames[ 0 ] = "ooo.vba.msforms.ScVbaListBox";
    }
    return aServiceNames;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Setting TEXT causes exception, don't do it<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "vbalistbox.hxx"
#include "vbanewfont.hxx"
#include <comphelper/anytostring.hxx>
#include <com/sun/star/script/ArrayWrapper.hpp>
#include <com/sun/star/form/validation/XValidatableFormComponent.hpp>
#include <ooo/vba/msforms/fmMultiSelect.hpp>

using namespace com::sun::star;
using namespace ooo::vba;

const static OUString TEXT( "Text" );
const static OUString SELECTEDITEMS( "SelectedItems" );
const static OUString ITEMS( "StringItemList" );

ScVbaListBox::ScVbaListBox( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext >& xContext, const uno::Reference< css::uno::XInterface >& xControl, const uno::Reference< frame::XModel >& xModel, AbstractGeometryAttributes* pGeomHelper ) : ListBoxImpl_BASE( xParent, xContext, xControl, xModel, pGeomHelper )
{
    mpListHelper.reset( new ListControlHelper( m_xProps ) );
}

// Attributes
void SAL_CALL
ScVbaListBox::setListIndex( const uno::Any& _value ) throw (uno::RuntimeException)
{
    sal_Int32 nIndex = 0;
    _value >>= nIndex;
    uno::Reference< XPropValue > xPropVal( Selected( nIndex ), uno::UNO_QUERY_THROW );
    xPropVal->setValue( uno::makeAny( sal_True ) );
}

uno::Any SAL_CALL
ScVbaListBox::getListIndex() throw (uno::RuntimeException)
{
    uno::Sequence< sal_Int16 > sSelection;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= sSelection;
    if ( sSelection.getLength() == 0 )
        return uno::Any( sal_Int32( -1 ) );
    return uno::Any( sSelection[ 0 ] );
}

uno::Any SAL_CALL
ScVbaListBox::getValue() throw (uno::RuntimeException)
{
    uno::Sequence< sal_Int16 > sSelection;
    uno::Sequence< OUString > sItems;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= sSelection;
    m_xProps->getPropertyValue( ITEMS ) >>= sItems;
    if( getMultiSelect() )
        throw uno::RuntimeException( "Attribute use invalid." , uno::Reference< uno::XInterface >() );
    uno::Any aRet;
    if ( sSelection.getLength() )
        aRet = uno::makeAny( sItems[ sSelection[ 0 ] ] );
    return aRet;
}

void SAL_CALL
ScVbaListBox::setValue( const uno::Any& _value ) throw (uno::RuntimeException)
{
    if( getMultiSelect() )
    {
        throw uno::RuntimeException( "Attribute use invalid." , uno::Reference< uno::XInterface >() );
    }
    OUString sValue = getAnyAsString( _value );
    uno::Sequence< OUString > sList;
    m_xProps->getPropertyValue( ITEMS ) >>= sList;
    uno::Sequence< sal_Int16 > nList;
    sal_Int16 nLength = static_cast<sal_Int16>( sList.getLength() );
    sal_Int16 nValue = -1;
    sal_Int16 i = 0;
    for( i = 0; i < nLength; i++ )
    {
        if( sList[i].equals( sValue ) )
        {
            nValue = i;
            break;
        }
    }
    if( nValue == -1 )
        throw uno::RuntimeException( "Attribute use invalid." , uno::Reference< uno::XInterface >() );

    uno::Sequence< sal_Int16 > nSelectedIndices(1);
    uno::Sequence< sal_Int16 > nOldSelectedIndices;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= nOldSelectedIndices;
    nSelectedIndices[ 0 ] = nValue;
    m_xProps->setPropertyValue( SELECTEDITEMS, uno::makeAny( nSelectedIndices ) );
    if ( nSelectedIndices != nOldSelectedIndices )
        fireClickEvent();
}

OUString SAL_CALL
ScVbaListBox::getText() throw (uno::RuntimeException)
{
    OUString result;
    getValue() >>= result;
    return result;
}

void SAL_CALL
ScVbaListBox::setText( const OUString& _text ) throw (uno::RuntimeException)
{
    setValue( uno::makeAny( _text ) ); // seems the same
}

sal_Int32 SAL_CALL
ScVbaListBox::getMultiSelect() throw (css::uno::RuntimeException)
{
    sal_Bool bMultiSelect = sal_False;
    m_xProps->getPropertyValue( "MultiSelection" ) >>= bMultiSelect;

    return bMultiSelect ? msforms::fmMultiSelect::fmMultiSelectMulti : msforms::fmMultiSelect::fmMultiSelectSingle;
}

void SAL_CALL
ScVbaListBox::setMultiSelect( sal_Int32 _multiselect ) throw (css::uno::RuntimeException)
{
    sal_Bool bBoolVal = false;
    switch ( _multiselect )
    {
        case  msforms::fmMultiSelect::fmMultiSelectMulti:
        case  msforms::fmMultiSelect::fmMultiSelectExtended:
            bBoolVal = sal_True;
            break;
        case msforms::fmMultiSelect::fmMultiSelectSingle:
            bBoolVal = sal_False;
            break;
        default:
            throw lang::IllegalArgumentException();
            break;
    }
    m_xProps->setPropertyValue( "MultiSelection" , uno::makeAny( bBoolVal ) );
}

css::uno::Any SAL_CALL
ScVbaListBox::Selected( sal_Int32 index ) throw (css::uno::RuntimeException)
{
    uno::Sequence< OUString > sList;
    m_xProps->getPropertyValue( ITEMS ) >>= sList;
    sal_Int16 nLength = static_cast< sal_Int16 >( sList.getLength() );
    // no choice but to do a horror cast as internally
    // the indices are but sal_Int16
    sal_Int16 nIndex = static_cast< sal_Int16 >( index );
    if( nIndex < 0 || nIndex >= nLength )
        throw uno::RuntimeException( "Error Number." , uno::Reference< uno::XInterface >() );
    m_nIndex = nIndex;
    return uno::makeAny( uno::Reference< XPropValue > ( new ScVbaPropValue( this ) ) );
}

// Methods
void SAL_CALL
ScVbaListBox::AddItem( const uno::Any& pvargItem, const uno::Any& pvargIndex ) throw (uno::RuntimeException)
{
    mpListHelper->AddItem( pvargItem, pvargIndex );
        }

void SAL_CALL
ScVbaListBox::removeItem( const uno::Any& index ) throw (uno::RuntimeException)
{
    mpListHelper->removeItem( index );
}

void SAL_CALL
ScVbaListBox::Clear(  ) throw (uno::RuntimeException)
{
    mpListHelper->Clear();
}

// this is called when something like the following vba code is used
// to set the selected state of particular entries in the Listbox
// ListBox1.Selected( 3 ) = false
//PropListener
void
ScVbaListBox::setValueEvent( const uno::Any& value )
{
    sal_Bool bValue = sal_False;
    if( !(value >>= bValue) )
        throw uno::RuntimeException( "Invalid type\n. need boolean." , uno::Reference< uno::XInterface >() );
    uno::Sequence< sal_Int16 > nList;
    m_xProps->getPropertyValue( SELECTEDITEMS ) >>= nList;
    sal_Int16 nLength = static_cast<sal_Int16>( nList.getLength() );
    sal_Int16 nIndex = m_nIndex;
    for( sal_Int16 i = 0; i < nLength; i++ )
    {
        if( nList[i] == nIndex )
        {
            if( bValue )
                return;
            else
            {
                for( ; i < nLength - 1; i++ )
                {
                    nList[i] = nList[i + 1];
                }
                nList.realloc( nLength - 1 );
                //m_xProps->setPropertyValue( sSourceName, uno::makeAny( nList ) );
                fireClickEvent();
        m_xProps->setPropertyValue( SELECTEDITEMS, uno::makeAny( nList ) );
                return;
            }
        }
    }
    if( bValue )
    {
        if( getMultiSelect() )
        {
            nList.realloc( nLength + 1 );
            nList[nLength] = nIndex;
        }
        else
        {
            nList.realloc( 1 );
            nList[0] = nIndex;
        }
        //m_xProps->setPropertyValue( sSourceName, uno::makeAny( nList ) );
        fireClickEvent();
        m_xProps->setPropertyValue( SELECTEDITEMS, uno::makeAny( nList ) );
    }
}

// this is called when something like the following vba code is used
// to determine the selected state of particular entries in the Listbox
// msgbox ListBox1.Selected( 3 )

css::uno::Any
ScVbaListBox::getValueEvent()
{
    uno::Sequence< sal_Int16 > nList;
    m_xProps->getPropertyValue( "SelectedItems" ) >>= nList;
    sal_Int32 nLength = nList.getLength();
    sal_Int32 nIndex = m_nIndex;

    for( sal_Int32 i = 0; i < nLength; i++ )
    {
        if( nList[i] == nIndex )
            return uno::makeAny( sal_True );
    }

    return uno::makeAny( sal_False );
}

void SAL_CALL
ScVbaListBox::setRowSource( const OUString& _rowsource ) throw (uno::RuntimeException)
{
    ScVbaControl::setRowSource( _rowsource );
    mpListHelper->setRowSource( _rowsource );
}

sal_Int32 SAL_CALL
ScVbaListBox::getListCount() throw (uno::RuntimeException)
{
    return mpListHelper->getListCount();
}

uno::Any SAL_CALL
ScVbaListBox::List( const ::uno::Any& pvargIndex, const uno::Any& pvarColumn ) throw (uno::RuntimeException)
{
    return mpListHelper->List( pvargIndex, pvarColumn );
}

uno::Reference< msforms::XNewFont > SAL_CALL ScVbaListBox::getFont() throw (uno::RuntimeException)
{
    return new VbaNewFont( this, mxContext, m_xProps );
}

OUString
ScVbaListBox::getServiceImplName()
{
    return OUString("ScVbaListBox");
}

uno::Sequence< OUString >
ScVbaListBox::getServiceNames()
{
    static uno::Sequence< OUString > aServiceNames;
    if ( aServiceNames.getLength() == 0 )
    {
        aServiceNames.realloc( 1 );
        aServiceNames[ 0 ] = "ooo.vba.msforms.ScVbaListBox";
    }
    return aServiceNames;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: op.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-26 18:05:30 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------------

#include <tools/solar.h>
#include <rtl/math.hxx>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#if defined( MAC ) || defined( ICC )
#include <stdlib.h>
#endif

#include "cell.hxx"
#include "rangenam.hxx"
#include "document.hxx"

#include "op.h"
#include "tool.h"
#include "math.h"
#include "decl.h"
#include "lotform.hxx"
#include "lotrange.hxx"

#include "root.hxx"

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif

extern sal_Char*    pAnsi;          // -> memory.cxx, Puffer zum Umwandeln von OEM->ANSI
extern sal_Char*    pErgebnis;      // -> memory.cxx, Ergebnispuffer
extern WKTYP        eTyp;           // -> filter.cxx, aktueller Dateityp
extern BOOL         bEOF;           // -> filter.cxx, zeigt Dateiende an
extern sal_Char*    pPuffer0;       // -> memory.cxx
extern sal_Char*    pPuffer1;
extern BYTE         nDefaultFormat; // -> tool.cxx, Default-Zellenformat
extern ScDocument*  pDoc;           // -> filter.cxx, Aufhaenger zum Dokumentzugriff
extern BYTE*        pFormelBuffer;  // -> memory.cxx, fuer

static UINT16       nDefWidth = ( UINT16 ) ( TWIPS_PER_CHAR * 10 );

void NI( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_BOF( SvStream& r, UINT16 n )
{
    r.SeekRel( 2 );        // Versionsnummer ueberlesen
}

void OP_EOF( SvStream& r, UINT16 n )
{
    bEOF = TRUE;
}

void OP_Integer( SvStream& r, UINT16 n )
{
    BYTE            nFormat;
    UINT16          nCol, nRow, nTab = 0;
    INT16           nValue;

    r >> nFormat >> nCol >> nRow >> nValue;

    ScValueCell*    pZelle = new ScValueCell( ( double ) nValue );
    pDoc->PutCell( nCol, nRow, nTab, pZelle, ( BOOL ) TRUE );

    // 0 Stellen nach'm Komma!
    SetFormat( nCol, nRow, nTab, nFormat, 0 );
}

void OP_Number( SvStream& r, UINT16 n )
{
    BYTE            nFormat;
    UINT16          nCol, nRow, nTab = 0;
    double          fValue;

    r >> nFormat >> nCol >> nRow >> fValue;

    fValue = ::rtl::math::round( fValue, 15 );
    ScValueCell*    pZelle = new ScValueCell( fValue );
    pDoc->PutCell( nCol, nRow, nTab, pZelle, ( BOOL ) TRUE );

    SetFormat( nCol, nRow, nTab, nFormat, nDezFloat );
}

void OP_Label( SvStream& r, UINT16 n )
{
    BYTE            nFormat;
    UINT16          nCol, nRow, nTab = 0;
    sal_Char        pText[ 256 ];

    r >> nFormat >> nCol >> nRow;
    n -= 5;

    r.Read( pText, n );
    pText[ n + 1 ] = 0;   // zur Sicherheit Nullterminator anhaengen
    // der Mega-Hack: bei Text wird HART Text als Format eingebrannt!!!!!!!
    nFormat &= 0x80;    // Bit 7 belassen
    nFormat |= 0x75;    // protected egal, special-text gesetzt

    // Sonderzeichenanpassung
    DosToSystem( pText );

    PutFormString( nCol, nRow, nTab, pText );

    SetFormat( nCol, nRow, nTab, nFormat, nDezStd );
}

void OP_Text( SvStream& r, UINT16 n )        // WK3
{
    UINT16          nRow;
    BYTE            nCol, nTab;
    sal_Char        pText[ 256 ];

    r >> nRow >> nTab >> nCol;
    n -= 4;

    r.Read( pText, n );
    pText[ n ] = 0;   // zur Sicherheit Nullterminator anhaengen

    PutFormString( nCol, nRow, nTab, pText );
}

void OP_Formula( SvStream& r, UINT16 n )
{
    BYTE                nFormat;
    UINT16              nCol, nRow, nTab = 0, nFormulaSize;

    r >> nFormat >> nCol >> nRow;
    r.SeekRel( 8 );    // Ergebnis ueberspringen
    r >> nFormulaSize;

    const ScTokenArray* pErg;
    INT32               nBytesLeft = nFormulaSize;
    ScAddress           aAddress( nCol, nRow, nTab );

    LotusToSc           aConv( r, pLotusRoot->eCharsetQ );
    aConv.Reset( aAddress );
    aConv.Convert( pErg, nBytesLeft );

    ScFormulaCell*      pZelle = new ScFormulaCell( pLotusRoot->pDoc, aAddress, pErg );

    pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );

    pDoc->PutCell( nCol, nRow, nTab, pZelle, ( BOOL ) TRUE );

    // nFormat = Standard -> Nachkommastellen wie Float
    SetFormat( nCol, nRow, nTab, nFormat, nDezFloat );
}

void OP_ColumnWidth( SvStream& r, UINT16 n )
{
    UINT16              nCol, nBreite, nTab = 0;
    BYTE                nWidthSpaces;

    r >> nCol >> nWidthSpaces;

    if( nWidthSpaces )
        // Annahme: 10cpi-Zeichensatz
        nBreite = ( UINT16 ) ( TWIPS_PER_CHAR * nWidthSpaces );
    else
    {
        pDoc->SetColFlags( nCol, 0, pDoc->GetColFlags( nCol, 0 ) | CR_HIDDEN );
        nBreite = nDefWidth;
    }

    pDoc->SetColWidth( nCol, nTab, nBreite );
}

void OP_NamedRange( SvStream& r, UINT16 n )
    {
    // POST:    waren Koordinaten ungueltig, wird nicht gespeichert
    UINT16              nColSt, nRowSt, nColEnd, nRowEnd;
    sal_Char            cPuffer[ 32 ];

    r.Read( cPuffer, 16 );

    r >> nColSt >> nRowSt >> nColEnd >> nRowEnd;

    LotusRange*         pRange;

    if( nColSt == nColEnd && nRowSt == nRowEnd )
        pRange = new LotusRange( nColSt, nRowSt );
    else
        pRange = new LotusRange( nColSt, nRowSt, nColEnd, nRowEnd );

    if( isdigit( *cPuffer ) )
    {   // erstes Zeichen im Namen eine Zahl -> 'A' vor Namen setzen
        *pAnsi = 'A';
        strcpy( pAnsi + 1, cPuffer );       // #100211# - checked
    }
    else
        strcpy( pAnsi, cPuffer );           // #100211# - checked

    DosToSystem( pAnsi );

    String              aTmp( pAnsi, pLotusRoot->eCharsetQ );

    ScfTools::ConvertToScDefinedName( aTmp );

    pLotusRoot->pRangeNames->Append( pRange, aTmp );
}

void OP_SymphNamedRange( SvStream& r, UINT16 n )
{
    // POST:    waren Koordinaten ungueltig, wird nicht gespeichert
    UINT16              nColSt, nRowSt, nColEnd, nRowEnd, nN = 0;
    BYTE                nType;
    sal_Char*           pName;
    sal_Char            cPuffer[ 32 ];

    r.Read( cPuffer, 16 );
    cPuffer[ 16 ] = 0;
    pName = cPuffer;

    r >> nColSt >> nRowSt >> nColEnd >> nRowEnd >> nType;

    LotusRange*         pRange;

    if( nType )
        pRange = new LotusRange( nColSt, nRowSt );
    else
        pRange = new LotusRange( nColSt, nRowSt, nColEnd, nRowEnd );

    if( isdigit( *cPuffer ) )
    {   // erstes Zeichen im Namen eine Zahl -> 'A' vor Namen setzen
        *pAnsi = 'A';
        strcpy( pAnsi + 1, cPuffer );       // #100211# - checked
    }
    else
        strcpy( pAnsi, cPuffer );           // #100211# - checked

    DosToSystem( pAnsi );

    String      aTmp( pAnsi, pLotusRoot->eCharsetQ );
    ScfTools::ConvertToScDefinedName( aTmp );

    pLotusRoot->pRangeNames->Append( pRange, aTmp );
}

void OP_Footer( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_Header( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_Margins( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_HiddenCols( SvStream& r, UINT16 n )
{
    UINT16      nByte, nBit, nCount;
    BYTE        nAkt;
    nCount = 0;

    for( nByte = 0 ; nByte < 32 ; nByte++ ) // 32 Bytes mit ...
    {
        r >> nAkt;
        for( nBit = 0 ; nBit < 8 ; nBit++ ) // ...jeweils 8 Bits = 256 Bits
        {
            if( nAkt & 0x01 )   // unterstes Bit gesetzt?
                // -> Hidden Col
                pDoc->SetColFlags( nCount, 0, pDoc->GetColFlags( nCount, 0 ) | CR_HIDDEN );

            nCount++;
            nAkt = nAkt / 2;    // der Nchste bitte...
        }
    }
}

void OP_Window1( SvStream& r, UINT16 n )
{
    r.SeekRel( 4 );    // Cursor Pos ueberspringen

    r >> nDefaultFormat;

    r.SeekRel( 1 );    // 'unused' ueberspringen

    r >> nDefWidth;

    r.SeekRel( n - 8 );  // und den Rest ueberspringen

    nDefWidth = ( UINT16 ) ( TWIPS_PER_CHAR * nDefWidth );

    // statt Defaulteinstellung in SC alle Cols zu Fuss setzen
    for( UINT16 nCol = 0 ; nCol <= MAXCOL ; nCol++ )
        pDoc->SetColWidth( nCol, 0, nDefWidth );
}

void OP_Blank( SvStream& r, UINT16 n )
{
    UINT16      nCol, nRow;
    BYTE        nFormat;
    r >> nFormat >> nCol >> nRow;

    SetFormat( nCol, nRow, 0, nFormat, nDezFloat );
}

<commit_msg>INTEGRATION: CWS rowlimit (1.7.200); FILE MERGED 2004/01/19 09:38:32 jmarmion 1.7.200.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short.<commit_after>/*************************************************************************
 *
 *  $RCSfile: op.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:03:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------------

#include <tools/solar.h>
#include <rtl/math.hxx>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#if defined( MAC ) || defined( ICC )
#include <stdlib.h>
#endif

#include "cell.hxx"
#include "rangenam.hxx"
#include "document.hxx"

#include "op.h"
#include "tool.h"
#include "math.h"
#include "decl.h"
#include "lotform.hxx"
#include "lotrange.hxx"

#include "root.hxx"

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif

extern sal_Char*    pAnsi;          // -> memory.cxx, Puffer zum Umwandeln von OEM->ANSI
extern sal_Char*    pErgebnis;      // -> memory.cxx, Ergebnispuffer
extern WKTYP        eTyp;           // -> filter.cxx, aktueller Dateityp
extern BOOL         bEOF;           // -> filter.cxx, zeigt Dateiende an
extern sal_Char*    pPuffer0;       // -> memory.cxx
extern sal_Char*    pPuffer1;
extern BYTE         nDefaultFormat; // -> tool.cxx, Default-Zellenformat
extern ScDocument*  pDoc;           // -> filter.cxx, Aufhaenger zum Dokumentzugriff
extern BYTE*        pFormelBuffer;  // -> memory.cxx, fuer

static UINT16       nDefWidth = ( UINT16 ) ( TWIPS_PER_CHAR * 10 );

void NI( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_BOF( SvStream& r, UINT16 n )
{
    r.SeekRel( 2 );        // Versionsnummer ueberlesen
}

void OP_EOF( SvStream& r, UINT16 n )
{
    bEOF = TRUE;
}

void OP_Integer( SvStream& r, UINT16 n )
{
    BYTE            nFormat;
    UINT16          nCol, nRow;
    SCTAB           nTab = 0;
    INT16           nValue;

    r >> nFormat >> nCol >> nRow >> nValue;

    ScValueCell*    pZelle = new ScValueCell( ( double ) nValue );
    pDoc->PutCell( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, pZelle, ( BOOL ) TRUE );

    // 0 Stellen nach'm Komma!
    SetFormat( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, nFormat, 0 );
}

void OP_Number( SvStream& r, UINT16 n )
{
    BYTE            nFormat;
    UINT16          nCol, nRow;
    SCTAB           nTab = 0;
    double          fValue;

    r >> nFormat >> nCol >> nRow >> fValue;

    fValue = ::rtl::math::round( fValue, 15 );
    ScValueCell*    pZelle = new ScValueCell( fValue );
    pDoc->PutCell( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, pZelle, ( BOOL ) TRUE );

    SetFormat( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, nFormat, nDezFloat );
}

void OP_Label( SvStream& r, UINT16 n )
{
    BYTE            nFormat;
    UINT16          nCol, nRow;
    SCTAB           nTab = 0;
    sal_Char        pText[ 256 ];

    r >> nFormat >> nCol >> nRow;
    n -= 5;

    r.Read( pText, n );
    pText[ n + 1 ] = 0;   // zur Sicherheit Nullterminator anhaengen
    // der Mega-Hack: bei Text wird HART Text als Format eingebrannt!!!!!!!
    nFormat &= 0x80;    // Bit 7 belassen
    nFormat |= 0x75;    // protected egal, special-text gesetzt

    // Sonderzeichenanpassung
    DosToSystem( pText );

    PutFormString( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, pText );

    SetFormat( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, nFormat, nDezStd );
}

void OP_Text( SvStream& r, UINT16 n )        // WK3
{
    UINT16          nRow;
    BYTE            nCol, nTab;
    sal_Char        pText[ 256 ];

    r >> nRow >> nTab >> nCol;
    n -= 4;

    r.Read( pText, n );
    pText[ n ] = 0;   // zur Sicherheit Nullterminator anhaengen

    PutFormString( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), pText );
}

void OP_Formula( SvStream& r, UINT16 n )
{
    BYTE                nFormat;
    UINT16              nCol, nRow, nFormulaSize;
    SCTAB                   nTab = 0;

    r >> nFormat >> nCol >> nRow;
    r.SeekRel( 8 );    // Ergebnis ueberspringen
    r >> nFormulaSize;

    const ScTokenArray* pErg;
    INT32               nBytesLeft = nFormulaSize;
    ScAddress           aAddress( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab );

    LotusToSc           aConv( r, pLotusRoot->eCharsetQ );
    aConv.Reset( aAddress );
    aConv.Convert( pErg, nBytesLeft );

    ScFormulaCell*      pZelle = new ScFormulaCell( pLotusRoot->pDoc, aAddress, pErg );

    pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );

    pDoc->PutCell( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, pZelle, ( BOOL ) TRUE );

    // nFormat = Standard -> Nachkommastellen wie Float
    SetFormat( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), nTab, nFormat, nDezFloat );
}

void OP_ColumnWidth( SvStream& r, UINT16 n )
{
    UINT16              nCol, nBreite;
    BYTE                nWidthSpaces;
    SCTAB                   nTab = 0;

    r >> nCol >> nWidthSpaces;

    if( nWidthSpaces )
        // Annahme: 10cpi-Zeichensatz
        nBreite = ( UINT16 ) ( TWIPS_PER_CHAR * nWidthSpaces );
    else
    {
        pDoc->SetColFlags( static_cast<SCCOL> (nCol), 0, pDoc->GetColFlags( static_cast<SCCOL> (nCol), 0 ) | CR_HIDDEN );
        nBreite = nDefWidth;
    }

    pDoc->SetColWidth( static_cast<SCCOL> (nCol), nTab, nBreite );
}

void OP_NamedRange( SvStream& r, UINT16 n )
    {
    // POST:    waren Koordinaten ungueltig, wird nicht gespeichert
    UINT16              nColSt, nRowSt, nColEnd, nRowEnd;
    sal_Char            cPuffer[ 32 ];

    r.Read( cPuffer, 16 );

    r >> nColSt >> nRowSt >> nColEnd >> nRowEnd;

    LotusRange*         pRange;

    if( nColSt == nColEnd && nRowSt == nRowEnd )
        pRange = new LotusRange( static_cast<SCCOL> (nColSt), static_cast<SCROW> (nRowSt) );
    else
        pRange = new LotusRange( static_cast<SCCOL> (nColSt), static_cast<SCROW> (nRowSt), static_cast<SCCOL> (nColEnd), static_cast<SCROW> (nRowEnd) );

    if( isdigit( *cPuffer ) )
    {   // erstes Zeichen im Namen eine Zahl -> 'A' vor Namen setzen
        *pAnsi = 'A';
        strcpy( pAnsi + 1, cPuffer );       // #100211# - checked
    }
    else
        strcpy( pAnsi, cPuffer );           // #100211# - checked

    DosToSystem( pAnsi );

    String              aTmp( pAnsi, pLotusRoot->eCharsetQ );

    ScfTools::ConvertToScDefinedName( aTmp );

    pLotusRoot->pRangeNames->Append( pRange, aTmp );
}

void OP_SymphNamedRange( SvStream& r, UINT16 n )
{
    // POST:    waren Koordinaten ungueltig, wird nicht gespeichert
    UINT16              nColSt, nRowSt, nColEnd, nRowEnd, nN = 0;
    BYTE                nType;
    sal_Char*           pName;
    sal_Char            cPuffer[ 32 ];

    r.Read( cPuffer, 16 );
    cPuffer[ 16 ] = 0;
    pName = cPuffer;

    r >> nColSt >> nRowSt >> nColEnd >> nRowEnd >> nType;

    LotusRange*         pRange;

    if( nType )
        pRange = new LotusRange( static_cast<SCCOL> (nColSt), static_cast<SCROW> (nRowSt) );
    else
        pRange = new LotusRange( static_cast<SCCOL> (nColSt), static_cast<SCROW> (nRowSt), static_cast<SCCOL> (nColEnd), static_cast<SCROW> (nRowEnd) );

    if( isdigit( *cPuffer ) )
    {   // erstes Zeichen im Namen eine Zahl -> 'A' vor Namen setzen
        *pAnsi = 'A';
        strcpy( pAnsi + 1, cPuffer );       // #100211# - checked
    }
    else
        strcpy( pAnsi, cPuffer );           // #100211# - checked

    DosToSystem( pAnsi );

    String      aTmp( pAnsi, pLotusRoot->eCharsetQ );
    ScfTools::ConvertToScDefinedName( aTmp );

    pLotusRoot->pRangeNames->Append( pRange, aTmp );
}

void OP_Footer( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_Header( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_Margins( SvStream& r, UINT16 n )
{
    r.SeekRel( n );
}

void OP_HiddenCols( SvStream& r, UINT16 n )
{
    UINT16      nByte, nBit;
    SCCOL       nCount;
    BYTE        nAkt;
    nCount = 0;

    for( nByte = 0 ; nByte < 32 ; nByte++ ) // 32 Bytes mit ...
    {
        r >> nAkt;
        for( nBit = 0 ; nBit < 8 ; nBit++ ) // ...jeweils 8 Bits = 256 Bits
        {
            if( nAkt & 0x01 )   // unterstes Bit gesetzt?
                // -> Hidden Col
                pDoc->SetColFlags( nCount, 0, pDoc->GetColFlags( nCount, 0 ) | CR_HIDDEN );

            nCount++;
            nAkt = nAkt / 2;    // der Nchste bitte...
        }
    }
}

void OP_Window1( SvStream& r, UINT16 n )
{
    r.SeekRel( 4 );    // Cursor Pos ueberspringen

    r >> nDefaultFormat;

    r.SeekRel( 1 );    // 'unused' ueberspringen

    r >> nDefWidth;

    r.SeekRel( n - 8 );  // und den Rest ueberspringen

    nDefWidth = ( UINT16 ) ( TWIPS_PER_CHAR * nDefWidth );

    // statt Defaulteinstellung in SC alle Cols zu Fuss setzen
    for( SCCOL nCol = 0 ; nCol <= MAXCOL ; nCol++ )
        pDoc->SetColWidth( nCol, 0, nDefWidth );
}

void OP_Blank( SvStream& r, UINT16 n )
{
    UINT16      nCol, nRow;
    BYTE        nFormat;
    r >> nFormat >> nCol >> nRow;

    SetFormat( static_cast<SCCOL> (nCol), static_cast<SCROW> (nRow), 0, nFormat, nDezFloat );
}

<|endoftext|>


<commit_before><commit_msg>testing<commit_after><|endoftext|>


<commit_before><commit_msg>fix TextBox value error, MaxLength is long in vba but short in libreoffice<commit_after><|endoftext|>