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

#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "base/utf_string_conversions.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/http/http_cache.h"
#include "net/socket/ssl_test_util.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/heap_profiler_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"

#if defined(OS_WIN)
#pragma warning(disable: 4996)
#endif

static const size_t kPathBufSize = 2048;

using WebKit::WebScriptController;

namespace {

// StatsTable initialization parameters.
const char* const kStatsFilePrefix = "testshell_";
int kStatsFileThreads = 20;
int kStatsFileCounters = 200;

void RemoveSharedMemoryFile(std::string& filename) {
  // Stats uses SharedMemory under the hood. On posix, this results in a file
  // on disk.
#if defined(OS_POSIX)
  base::SharedMemory memory;
  memory.Delete(UTF8ToWide(filename));
#endif
}

}  // namespace

int main(int argc, char* argv[]) {
  base::EnableInProcessStackDumping();
  base::EnableTerminationOnHeapCorruption();

  // Some tests may use base::Singleton<>, thus we need to instanciate
  // the AtExitManager or else we will leak objects.
  base::AtExitManager at_exit_manager;

  TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
  CommandLine::Init(argc, argv);
  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();

  TestShellPlatformDelegate platform(parsed_command_line);

  if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
    TestShell::ShowStartupDebuggingDialog();

  if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
    exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
  }

  // Allocate a message loop for this thread.  Although it is not used
  // directly, its constructor sets up some necessary state.
  MessageLoopForUI main_message_loop;

  bool suppress_error_dialogs = (
       base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") ||
       parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
       parsed_command_line.HasSwitch(test_shell::kLayoutTests));
  bool layout_test_mode =
      parsed_command_line.HasSwitch(test_shell::kLayoutTests);
  bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme);
  bool classic_theme =
      parsed_command_line.HasSwitch(test_shell::kClassicTheme);
#if defined(OS_WIN)
  bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) ||
      parsed_command_line.HasSwitch(test_shell::kGenericTheme);
#else
  // Stop compiler warnings about unused variables.
  ux_theme = ux_theme;
#endif

  bool enable_gp_fault_error_box = false;
  enable_gp_fault_error_box =
      parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);

  bool allow_external_pages =
      parsed_command_line.HasSwitch(test_shell::kAllowExternalPages);

  TestShell::InitLogging(suppress_error_dialogs,
                         layout_test_mode,
                         enable_gp_fault_error_box);

  // Initialize WebKit for this scope.
  TestShellWebKitInit test_shell_webkit_init(layout_test_mode);

  // Suppress abort message in v8 library in debugging mode (but not
  // actually under a debugger).  V8 calls abort() when it hits
  // assertion errors.
  if (suppress_error_dialogs) {
    platform.SuppressErrorReporting();
  }

  if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
    base::TraceLog::StartTracing();

  net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;

  // This is a special mode where JS helps the browser implement
  // playback/record mode.  Generally, in this mode, some functions
  // of client-side randomness are removed.  For example, in
  // this mode Math.random() and Date.getTime() may not return
  // values which vary.
  bool playback_mode =
    parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
  bool record_mode =
    parsed_command_line.HasSwitch(test_shell::kRecordMode);

  if (playback_mode)
    cache_mode = net::HttpCache::PLAYBACK;
  else if (record_mode)
    cache_mode = net::HttpCache::RECORD;

  if (layout_test_mode ||
      parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
    net::CookieMonster::EnableFileScheme();

  FilePath cache_path =
      parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir);
  // If the cache_path is empty and it's layout_test_mode, leave it empty
  // so we use an in-memory cache. This makes running multiple test_shells
  // in parallel less flaky.
  if (cache_path.empty() && !layout_test_mode) {
    PathService::Get(base::DIR_EXE, &cache_path);
    cache_path = cache_path.AppendASCII("cache");
  }

  // Initializing with a default context, which means no on-disk cookie DB,
  // and no support for directory listings.
  SimpleResourceLoaderBridge::Init(
      new TestShellRequestContext(cache_path, cache_mode, layout_test_mode));

  // Load ICU data tables
  icu_util::Initialize();

  // Config the network module so it has access to a limited set of resources.
  net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);

  // On Linux and Mac, load the test root certificate.
  net::TestServerLauncher ssl_util;
  ssl_util.LoadTestRootCert();

  platform.InitializeGUI();

  TestShell::InitializeTestShell(layout_test_mode, allow_external_pages);

  if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
    TestShell::SetAllowScriptsToCloseWindows();

  // Disable user themes for layout tests so pixel tests are consistent.
#if defined(OS_WIN)
  TestShellWebTheme::Engine engine;
#endif
  if (classic_theme)
    platform.SelectUnifiedTheme();
#if defined(OS_WIN)
  if (generic_theme)
    test_shell_webkit_init.SetThemeEngine(&engine);
#endif

  if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
    const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
        test_shell::kTestShellTimeOut);
    int timeout_ms =
        static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str())));
    if (timeout_ms > 0)
      TestShell::SetFileTestTimeout(timeout_ms);
  }

  // Treat the first loose value as the initial URL to open.
  GURL starting_url;

  // Default to a homepage if we're interactive.
  if (!layout_test_mode) {
    FilePath path;
    PathService::Get(base::DIR_SOURCE_ROOT, &path);
    path = path.AppendASCII("webkit");
    path = path.AppendASCII("data");
    path = path.AppendASCII("test_shell");
    path = path.AppendASCII("index.html");
    starting_url = net::FilePathToFileURL(path);
  }

  std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues();
  if (loose_values.size() > 0) {
    GURL url(WideToUTF16Hack(loose_values[0]));
    if (url.is_valid()) {
      starting_url = url;
    } else {
      // Treat as a file path
      starting_url =
          net::FilePathToFileURL(FilePath::FromWStringHack(loose_values[0]));
    }
  }

  std::wstring js_flags =
    parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
  // Test shell always exposes the GC.
  js_flags += L" --expose-gc";
  webkit_glue::SetJavaScriptFlags(js_flags);
  // Expose GCController to JavaScript.
  WebScriptController::registerExtension(extensions_v8::GCExtension::Get());

  if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
    WebScriptController::registerExtension(
        extensions_v8::ProfilerExtension::Get());
  }

  if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) {
    WebScriptController::registerExtension(
        extensions_v8::HeapProfilerExtension::Get());
  }

  // Load and initialize the stats table.  Attempt to construct a somewhat
  // unique name to isolate separate instances from each other.

  // truncate the random # to 32 bits for the benefit of Mac OS X, to
  // avoid tripping over its maximum shared memory segment name length
  std::string stats_filename =
      kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL);
  RemoveSharedMemoryFile(stats_filename);
  StatsTable *table = new StatsTable(stats_filename,
      kStatsFileThreads,
      kStatsFileCounters);
  StatsTable::set_current(table);

  TestShell* shell;
  if (TestShell::CreateNewWindow(starting_url, &shell)) {
    if (record_mode || playback_mode) {
      platform.SetWindowPositionForRecording(shell);
      WebScriptController::registerExtension(
          extensions_v8::PlaybackExtension::Get());
    }

    shell->Show(WebKit::WebNavigationPolicyNewWindow);

    if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
      shell->DumpStatsTableOnExit();

    bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
    if ((record_mode || playback_mode) && !no_events) {
      FilePath script_path = cache_path;
      // Create the cache directory in case it doesn't exist.
      file_util::CreateDirectory(cache_path);
      script_path = script_path.AppendASCII("script.log");
      if (record_mode)
        base::EventRecorder::current()->StartRecording(script_path);
      if (playback_mode)
        base::EventRecorder::current()->StartPlayback(script_path);
    }

    if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
      base::MemoryDebug::SetMemoryInUseEnabled(true);
      // Dump all in use memory at startup
      base::MemoryDebug::DumpAllMemoryInUse();
    }

    // See if we need to run the tests.
    if (layout_test_mode) {
      // Set up for the kind of test requested.
      TestShell::TestParams params;
      if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
        // The pixel test flag also gives the image file name to use.
        params.dump_pixels = true;
        params.pixel_file_name = parsed_command_line.GetSwitchValue(
            test_shell::kDumpPixels);
        if (params.pixel_file_name.size() == 0) {
          fprintf(stderr, "No file specified for pixel tests");
          exit(1);
        }
      }
      if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
          params.dump_tree = false;
      }

      if (!starting_url.is_valid()) {
        // Watch stdin for URLs.
        char filenameBuffer[kPathBufSize];
        while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
          // When running layout tests we pass new line separated
          // tests to TestShell. Each line is a space separated list
          // of filename, timeout and expected pixel hash. The timeout
          // and the pixel hash are optional.
          char* newLine = strchr(filenameBuffer, '\n');
          if (newLine)
            *newLine = '\0';
          if (!*filenameBuffer)
            continue;

          params.test_url = strtok(filenameBuffer, " ");

          // Set the current path to the directory that contains the test
          // files. This is because certain test file may use the relative
          // path.
          GURL test_url(params.test_url);
          FilePath test_file_path;
          net::FileURLToFilePath(test_url, &test_file_path);
          file_util::SetCurrentDirectory(test_file_path.DirName());

          int old_timeout_ms = TestShell::GetLayoutTestTimeout();

          char* timeout = strtok(NULL, " ");
          if (timeout) {
            TestShell::SetFileTestTimeout(atoi(timeout));
            char* pixel_hash = strtok(NULL, " ");
            if (pixel_hash)
              params.pixel_hash = pixel_hash;
          }

          if (!TestShell::RunFileTest(params))
            break;

          TestShell::SetFileTestTimeout(old_timeout_ms);
        }
      } else {
        // TODO(ojan): Provide a way for run-singly tests to pass
        // in a hash and then set params.pixel_hash here.
        params.test_url = WideToUTF8(loose_values[0]);
        TestShell::RunFileTest(params);
      }

      shell->CallJSGC();
      shell->CallJSGC();

      // When we finish the last test, cleanup the LayoutTestController.
      // It may have references to not-yet-cleaned up windows.  By
      // cleaning up here we help purify reports.
      shell->ResetTestController();

      // Flush any remaining messages before we kill ourselves.
      // http://code.google.com/p/chromium/issues/detail?id=9500
      MessageLoop::current()->RunAllPending();
    } else {
      MessageLoop::current()->Run();
    }

    if (record_mode)
      base::EventRecorder::current()->StopRecording();
    if (playback_mode)
      base::EventRecorder::current()->StopPlayback();
  }

  TestShell::ShutdownTestShell();
  TestShell::CleanupLogging();

  // Tear down shared StatsTable; prevents unit_tests from leaking it.
  StatsTable::set_current(NULL);
  delete table;
  RemoveSharedMemoryFile(stats_filename);

  return 0;
}
<commit_msg>test_shell: allow relative paths on the command line<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "base/utf_string_conversions.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/http/http_cache.h"
#include "net/socket/ssl_test_util.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScriptController.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/heap_profiler_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"

#if defined(OS_WIN)
#pragma warning(disable: 4996)
#endif

static const size_t kPathBufSize = 2048;

using WebKit::WebScriptController;

namespace {

// StatsTable initialization parameters.
const char* const kStatsFilePrefix = "testshell_";
int kStatsFileThreads = 20;
int kStatsFileCounters = 200;

void RemoveSharedMemoryFile(std::string& filename) {
  // Stats uses SharedMemory under the hood. On posix, this results in a file
  // on disk.
#if defined(OS_POSIX)
  base::SharedMemory memory;
  memory.Delete(UTF8ToWide(filename));
#endif
}

}  // namespace

int main(int argc, char* argv[]) {
  base::EnableInProcessStackDumping();
  base::EnableTerminationOnHeapCorruption();

  // Some tests may use base::Singleton<>, thus we need to instanciate
  // the AtExitManager or else we will leak objects.
  base::AtExitManager at_exit_manager;

  TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
  CommandLine::Init(argc, argv);
  const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();

  TestShellPlatformDelegate platform(parsed_command_line);

  if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
    TestShell::ShowStartupDebuggingDialog();

  if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
    exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
  }

  // Allocate a message loop for this thread.  Although it is not used
  // directly, its constructor sets up some necessary state.
  MessageLoopForUI main_message_loop;

  bool suppress_error_dialogs = (
       base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") ||
       parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
       parsed_command_line.HasSwitch(test_shell::kLayoutTests));
  bool layout_test_mode =
      parsed_command_line.HasSwitch(test_shell::kLayoutTests);
  bool ux_theme = parsed_command_line.HasSwitch(test_shell::kUxTheme);
  bool classic_theme =
      parsed_command_line.HasSwitch(test_shell::kClassicTheme);
#if defined(OS_WIN)
  bool generic_theme = (layout_test_mode && !ux_theme && !classic_theme) ||
      parsed_command_line.HasSwitch(test_shell::kGenericTheme);
#else
  // Stop compiler warnings about unused variables.
  ux_theme = ux_theme;
#endif

  bool enable_gp_fault_error_box = false;
  enable_gp_fault_error_box =
      parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);

  bool allow_external_pages =
      parsed_command_line.HasSwitch(test_shell::kAllowExternalPages);

  TestShell::InitLogging(suppress_error_dialogs,
                         layout_test_mode,
                         enable_gp_fault_error_box);

  // Initialize WebKit for this scope.
  TestShellWebKitInit test_shell_webkit_init(layout_test_mode);

  // Suppress abort message in v8 library in debugging mode (but not
  // actually under a debugger).  V8 calls abort() when it hits
  // assertion errors.
  if (suppress_error_dialogs) {
    platform.SuppressErrorReporting();
  }

  if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
    base::TraceLog::StartTracing();

  net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;

  // This is a special mode where JS helps the browser implement
  // playback/record mode.  Generally, in this mode, some functions
  // of client-side randomness are removed.  For example, in
  // this mode Math.random() and Date.getTime() may not return
  // values which vary.
  bool playback_mode =
    parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
  bool record_mode =
    parsed_command_line.HasSwitch(test_shell::kRecordMode);

  if (playback_mode)
    cache_mode = net::HttpCache::PLAYBACK;
  else if (record_mode)
    cache_mode = net::HttpCache::RECORD;

  if (layout_test_mode ||
      parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
    net::CookieMonster::EnableFileScheme();

  FilePath cache_path =
      parsed_command_line.GetSwitchValuePath(test_shell::kCacheDir);
  // If the cache_path is empty and it's layout_test_mode, leave it empty
  // so we use an in-memory cache. This makes running multiple test_shells
  // in parallel less flaky.
  if (cache_path.empty() && !layout_test_mode) {
    PathService::Get(base::DIR_EXE, &cache_path);
    cache_path = cache_path.AppendASCII("cache");
  }

  // Initializing with a default context, which means no on-disk cookie DB,
  // and no support for directory listings.
  SimpleResourceLoaderBridge::Init(
      new TestShellRequestContext(cache_path, cache_mode, layout_test_mode));

  // Load ICU data tables
  icu_util::Initialize();

  // Config the network module so it has access to a limited set of resources.
  net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);

  // On Linux and Mac, load the test root certificate.
  net::TestServerLauncher ssl_util;
  ssl_util.LoadTestRootCert();

  platform.InitializeGUI();

  TestShell::InitializeTestShell(layout_test_mode, allow_external_pages);

  if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
    TestShell::SetAllowScriptsToCloseWindows();

  // Disable user themes for layout tests so pixel tests are consistent.
#if defined(OS_WIN)
  TestShellWebTheme::Engine engine;
#endif
  if (classic_theme)
    platform.SelectUnifiedTheme();
#if defined(OS_WIN)
  if (generic_theme)
    test_shell_webkit_init.SetThemeEngine(&engine);
#endif

  if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
    const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
        test_shell::kTestShellTimeOut);
    int timeout_ms =
        static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str())));
    if (timeout_ms > 0)
      TestShell::SetFileTestTimeout(timeout_ms);
  }

  // Treat the first loose value as the initial URL to open.
  GURL starting_url;

  // Default to a homepage if we're interactive.
  if (!layout_test_mode) {
    FilePath path;
    PathService::Get(base::DIR_SOURCE_ROOT, &path);
    path = path.AppendASCII("webkit");
    path = path.AppendASCII("data");
    path = path.AppendASCII("test_shell");
    path = path.AppendASCII("index.html");
    starting_url = net::FilePathToFileURL(path);
  }

  std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues();
  if (loose_values.size() > 0) {
    GURL url(WideToUTF16Hack(loose_values[0]));
    if (url.is_valid()) {
      starting_url = url;
    } else {
      // Treat as a relative file path.
      FilePath path = FilePath::FromWStringHack(loose_values[0]);
      file_util::AbsolutePath(&path);
      starting_url = net::FilePathToFileURL(path);
    }
  }

  std::wstring js_flags =
    parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
  // Test shell always exposes the GC.
  js_flags += L" --expose-gc";
  webkit_glue::SetJavaScriptFlags(js_flags);
  // Expose GCController to JavaScript.
  WebScriptController::registerExtension(extensions_v8::GCExtension::Get());

  if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
    WebScriptController::registerExtension(
        extensions_v8::ProfilerExtension::Get());
  }

  if (parsed_command_line.HasSwitch(test_shell::kHeapProfiler)) {
    WebScriptController::registerExtension(
        extensions_v8::HeapProfilerExtension::Get());
  }

  // Load and initialize the stats table.  Attempt to construct a somewhat
  // unique name to isolate separate instances from each other.

  // truncate the random # to 32 bits for the benefit of Mac OS X, to
  // avoid tripping over its maximum shared memory segment name length
  std::string stats_filename =
      kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL);
  RemoveSharedMemoryFile(stats_filename);
  StatsTable *table = new StatsTable(stats_filename,
      kStatsFileThreads,
      kStatsFileCounters);
  StatsTable::set_current(table);

  TestShell* shell;
  if (TestShell::CreateNewWindow(starting_url, &shell)) {
    if (record_mode || playback_mode) {
      platform.SetWindowPositionForRecording(shell);
      WebScriptController::registerExtension(
          extensions_v8::PlaybackExtension::Get());
    }

    shell->Show(WebKit::WebNavigationPolicyNewWindow);

    if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
      shell->DumpStatsTableOnExit();

    bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
    if ((record_mode || playback_mode) && !no_events) {
      FilePath script_path = cache_path;
      // Create the cache directory in case it doesn't exist.
      file_util::CreateDirectory(cache_path);
      script_path = script_path.AppendASCII("script.log");
      if (record_mode)
        base::EventRecorder::current()->StartRecording(script_path);
      if (playback_mode)
        base::EventRecorder::current()->StartPlayback(script_path);
    }

    if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
      base::MemoryDebug::SetMemoryInUseEnabled(true);
      // Dump all in use memory at startup
      base::MemoryDebug::DumpAllMemoryInUse();
    }

    // See if we need to run the tests.
    if (layout_test_mode) {
      // Set up for the kind of test requested.
      TestShell::TestParams params;
      if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
        // The pixel test flag also gives the image file name to use.
        params.dump_pixels = true;
        params.pixel_file_name = parsed_command_line.GetSwitchValue(
            test_shell::kDumpPixels);
        if (params.pixel_file_name.size() == 0) {
          fprintf(stderr, "No file specified for pixel tests");
          exit(1);
        }
      }
      if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
          params.dump_tree = false;
      }

      if (!starting_url.is_valid()) {
        // Watch stdin for URLs.
        char filenameBuffer[kPathBufSize];
        while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
          // When running layout tests we pass new line separated
          // tests to TestShell. Each line is a space separated list
          // of filename, timeout and expected pixel hash. The timeout
          // and the pixel hash are optional.
          char* newLine = strchr(filenameBuffer, '\n');
          if (newLine)
            *newLine = '\0';
          if (!*filenameBuffer)
            continue;

          params.test_url = strtok(filenameBuffer, " ");

          // Set the current path to the directory that contains the test
          // files. This is because certain test file may use the relative
          // path.
          GURL test_url(params.test_url);
          FilePath test_file_path;
          net::FileURLToFilePath(test_url, &test_file_path);
          file_util::SetCurrentDirectory(test_file_path.DirName());

          int old_timeout_ms = TestShell::GetLayoutTestTimeout();

          char* timeout = strtok(NULL, " ");
          if (timeout) {
            TestShell::SetFileTestTimeout(atoi(timeout));
            char* pixel_hash = strtok(NULL, " ");
            if (pixel_hash)
              params.pixel_hash = pixel_hash;
          }

          if (!TestShell::RunFileTest(params))
            break;

          TestShell::SetFileTestTimeout(old_timeout_ms);
        }
      } else {
        // TODO(ojan): Provide a way for run-singly tests to pass
        // in a hash and then set params.pixel_hash here.
        params.test_url = WideToUTF8(loose_values[0]);
        TestShell::RunFileTest(params);
      }

      shell->CallJSGC();
      shell->CallJSGC();

      // When we finish the last test, cleanup the LayoutTestController.
      // It may have references to not-yet-cleaned up windows.  By
      // cleaning up here we help purify reports.
      shell->ResetTestController();

      // Flush any remaining messages before we kill ourselves.
      // http://code.google.com/p/chromium/issues/detail?id=9500
      MessageLoop::current()->RunAllPending();
    } else {
      MessageLoop::current()->Run();
    }

    if (record_mode)
      base::EventRecorder::current()->StopRecording();
    if (playback_mode)
      base::EventRecorder::current()->StopPlayback();
  }

  TestShell::ShutdownTestShell();
  TestShell::CleanupLogging();

  // Tear down shared StatsTable; prevents unit_tests from leaking it.
  StatsTable::set_current(NULL);
  delete table;
  RemoveSharedMemoryFile(stats_filename);

  return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include <OLEHandler.hxx>
#include <PropertyMap.hxx>
#include "GraphicHelpers.hxx"

#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include <rtl/oustringostreaminserter.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include "dmapperLoggers.hxx"

namespace writerfilter {
namespace dmapper {

using namespace ::com::sun::star;

OLEHandler::OLEHandler() :
LoggedProperties(dmapper_logger, "OLEHandler"),
m_nDxaOrig(0),
m_nDyaOrig(0),
    m_nWrapMode(1)
{
}

OLEHandler::~OLEHandler()
{
}

void OLEHandler::lcl_attribute(Id rName, Value & rVal)
{
    rtl::OUString sStringValue = rVal.getString();
    (void)rName;
    switch( rName )
    {
        case NS_ooxml::LN_CT_OLEObject_Type:
            m_sObjectType = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ProgID:
            m_sProgId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ShapeID:
            m_sShapeId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_DrawAspect:
            m_sDrawAspect = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ObjectID:
            m_sObjectId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_r_id:
            m_sr_id = sStringValue;
        break;
        case NS_ooxml::LN_inputstream:
            rVal.getAny() >>= m_xInputStream;
        break;
        case NS_ooxml::LN_CT_Object_dxaOrig:
            m_nDxaOrig = rVal.getInt();
        break;
        case NS_ooxml::LN_CT_Object_dyaOrig:
            m_nDyaOrig = rVal.getInt();
        break;
        case NS_ooxml::LN_shape:
        {
            uno::Reference< drawing::XShape > xTempShape;
            rVal.getAny() >>= xTempShape;
            if( xTempShape.is() )
            {
                m_xShape.set( xTempShape );

                try
                {
                    m_aShapeSize = xTempShape->getSize();
                    m_aShapePosition = xTempShape->getPosition();

                    uno::Reference< beans::XPropertySet > xShapeProps( xTempShape, uno::UNO_QUERY_THROW );
                    PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();

                    xShapeProps->getPropertyValue( rNameSupplier.GetName( PROP_BITMAP ) ) >>= m_xReplacement;

                    xShapeProps->setPropertyValue(
                        rNameSupplier.GetName( PROP_SURROUND ),
                        uno::makeAny( m_nWrapMode ) );
                }
                catch( const uno::Exception& e )
                {
                    SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
                }
            }
        }
        break;
        default:
            OSL_FAIL( "unknown attribute");
    }
}

void OLEHandler::lcl_sprm(Sprm & rSprm)
{
    sal_uInt32 nSprmId = rSprm.getId();
    switch( nSprmId )
    {
        case NS_ooxml::LN_OLEObject_OLEObject:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            if( pProperties.get())
            {
                pProperties->resolve(*this);
            }
        }
        break;
        case NS_ooxml::LN_wrap_wrap:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            if ( pProperties.get( ) )
            {
                WrapHandlerPtr pHandler( new WrapHandler );
                pProperties->resolve( *pHandler );

                m_nWrapMode = pHandler->getWrapMode( );

                try
                {
                    uno::Reference< beans::XPropertySet > xShapeProps( m_xShape, uno::UNO_QUERY_THROW );
                    PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();

                    xShapeProps->setPropertyValue(
                        rNameSupplier.GetName( PROP_SURROUND ),
                        uno::makeAny( m_nWrapMode ) );
                }
                catch( const uno::Exception& e )
                {
                    SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
                }
            }
        }
        break;
        default:
        {
            OSL_FAIL( "unknown attribute");
        }
    }
}

::rtl::OUString OLEHandler::copyOLEOStream( uno::Reference< text::XTextDocument > xTextDocument )
{
    ::rtl::OUString sRet;
    if( !m_xInputStream.is( ) )
        return sRet;
    try
    {
        uno::Reference < lang::XMultiServiceFactory > xFactory(xTextDocument, uno::UNO_QUERY_THROW);
        uno::Reference< document::XEmbeddedObjectResolver > xEmbeddedResolver(
            xFactory->createInstance(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.ImportEmbeddedObjectResolver" ))), uno::UNO_QUERY_THROW );
        //hack to work with the ImportEmbeddedObjectResolver
        static sal_Int32 nObjectCount = 100;
        uno::Reference< container::XNameAccess > xNA( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        ::rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("Obj" ));
        aURL += ::rtl::OUString::valueOf( nObjectCount++ );
        uno::Reference < io::XOutputStream > xOLEStream;
        if( (xNA->getByName( aURL ) >>= xOLEStream) && xOLEStream.is() )
        {
            const sal_Int32 nReadRequest = 0x1000;
            uno::Sequence< sal_Int8 > aData;

            while( true )
            {
                sal_Int32 nRead = m_xInputStream->readBytes( aData, nReadRequest );
                xOLEStream->writeBytes( aData );
                if( nRead < nReadRequest )
                {
                    xOLEStream->closeOutput();
                    break;
                }
            }

            static const ::rtl::OUString sProtocol = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("vnd.sun.star.EmbeddedObject:" ));
            ::rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) );
            sRet = aPersistName.copy( sProtocol.getLength() );

        }
        uno::Reference< lang::XComponent > xComp( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        xComp->dispose();
    }
    catch( const uno::Exception& )
    {
        OSL_FAIL("exception in OLEHandler::createOLEObject");
    }
    return sRet;
}

} //namespace dmapper
} //namespace writerfilter

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>n#758883 dmapper: set wrap mode even if determining the position failed<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include <OLEHandler.hxx>
#include <PropertyMap.hxx>
#include "GraphicHelpers.hxx"

#include <doctok/resourceids.hxx>
#include <ooxml/resourceids.hxx>
#include <rtl/oustringostreaminserter.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/drawing/XShape.hpp>
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#include <com/sun/star/embed/XEmbedObjectCreator.hpp>
#include <com/sun/star/graphic/XGraphic.hpp>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>

#include "dmapperLoggers.hxx"

namespace writerfilter {
namespace dmapper {

using namespace ::com::sun::star;

OLEHandler::OLEHandler() :
LoggedProperties(dmapper_logger, "OLEHandler"),
m_nDxaOrig(0),
m_nDyaOrig(0),
    m_nWrapMode(1)
{
}

OLEHandler::~OLEHandler()
{
}

void OLEHandler::lcl_attribute(Id rName, Value & rVal)
{
    rtl::OUString sStringValue = rVal.getString();
    (void)rName;
    switch( rName )
    {
        case NS_ooxml::LN_CT_OLEObject_Type:
            m_sObjectType = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ProgID:
            m_sProgId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ShapeID:
            m_sShapeId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_DrawAspect:
            m_sDrawAspect = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_ObjectID:
            m_sObjectId = sStringValue;
        break;
        case NS_ooxml::LN_CT_OLEObject_r_id:
            m_sr_id = sStringValue;
        break;
        case NS_ooxml::LN_inputstream:
            rVal.getAny() >>= m_xInputStream;
        break;
        case NS_ooxml::LN_CT_Object_dxaOrig:
            m_nDxaOrig = rVal.getInt();
        break;
        case NS_ooxml::LN_CT_Object_dyaOrig:
            m_nDyaOrig = rVal.getInt();
        break;
        case NS_ooxml::LN_shape:
        {
            uno::Reference< drawing::XShape > xTempShape;
            rVal.getAny() >>= xTempShape;
            if( xTempShape.is() )
            {
                m_xShape.set( xTempShape );
                uno::Reference< beans::XPropertySet > xShapeProps( xTempShape, uno::UNO_QUERY );
                PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();

                try
                {
                    m_aShapeSize = xTempShape->getSize();
                    m_aShapePosition = xTempShape->getPosition();

                    xShapeProps->getPropertyValue( rNameSupplier.GetName( PROP_BITMAP ) ) >>= m_xReplacement;
                }
                catch( const uno::Exception& e )
                {
                    SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
                }

                try
                {
                    xShapeProps->setPropertyValue(
                        rNameSupplier.GetName( PROP_SURROUND ),
                        uno::makeAny( m_nWrapMode ) );
                }
                catch( const uno::Exception& e )
                {
                    SAL_WARN("writerfilter", "Exception while setting wrap mode: " << e.Message);
                }
            }
        }
        break;
        default:
            OSL_FAIL( "unknown attribute");
    }
}

void OLEHandler::lcl_sprm(Sprm & rSprm)
{
    sal_uInt32 nSprmId = rSprm.getId();
    switch( nSprmId )
    {
        case NS_ooxml::LN_OLEObject_OLEObject:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            if( pProperties.get())
            {
                pProperties->resolve(*this);
            }
        }
        break;
        case NS_ooxml::LN_wrap_wrap:
        {
            writerfilter::Reference<Properties>::Pointer_t pProperties = rSprm.getProps();
            if ( pProperties.get( ) )
            {
                WrapHandlerPtr pHandler( new WrapHandler );
                pProperties->resolve( *pHandler );

                m_nWrapMode = pHandler->getWrapMode( );

                try
                {
                    uno::Reference< beans::XPropertySet > xShapeProps( m_xShape, uno::UNO_QUERY_THROW );
                    PropertyNameSupplier& rNameSupplier = PropertyNameSupplier::GetPropertyNameSupplier();

                    xShapeProps->setPropertyValue(
                        rNameSupplier.GetName( PROP_SURROUND ),
                        uno::makeAny( m_nWrapMode ) );
                }
                catch( const uno::Exception& e )
                {
                    SAL_WARN("writerfilter", "Exception in OLE Handler: " << e.Message);
                }
            }
        }
        break;
        default:
        {
            OSL_FAIL( "unknown attribute");
        }
    }
}

::rtl::OUString OLEHandler::copyOLEOStream( uno::Reference< text::XTextDocument > xTextDocument )
{
    ::rtl::OUString sRet;
    if( !m_xInputStream.is( ) )
        return sRet;
    try
    {
        uno::Reference < lang::XMultiServiceFactory > xFactory(xTextDocument, uno::UNO_QUERY_THROW);
        uno::Reference< document::XEmbeddedObjectResolver > xEmbeddedResolver(
            xFactory->createInstance(
                ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.document.ImportEmbeddedObjectResolver" ))), uno::UNO_QUERY_THROW );
        //hack to work with the ImportEmbeddedObjectResolver
        static sal_Int32 nObjectCount = 100;
        uno::Reference< container::XNameAccess > xNA( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        ::rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("Obj" ));
        aURL += ::rtl::OUString::valueOf( nObjectCount++ );
        uno::Reference < io::XOutputStream > xOLEStream;
        if( (xNA->getByName( aURL ) >>= xOLEStream) && xOLEStream.is() )
        {
            const sal_Int32 nReadRequest = 0x1000;
            uno::Sequence< sal_Int8 > aData;

            while( true )
            {
                sal_Int32 nRead = m_xInputStream->readBytes( aData, nReadRequest );
                xOLEStream->writeBytes( aData );
                if( nRead < nReadRequest )
                {
                    xOLEStream->closeOutput();
                    break;
                }
            }

            static const ::rtl::OUString sProtocol = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("vnd.sun.star.EmbeddedObject:" ));
            ::rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) );
            sRet = aPersistName.copy( sProtocol.getLength() );

        }
        uno::Reference< lang::XComponent > xComp( xEmbeddedResolver, uno::UNO_QUERY_THROW );
        xComp->dispose();
    }
    catch( const uno::Exception& )
    {
        OSL_FAIL("exception in OLEHandler::createOLEObject");
    }
    return sRet;
}

} //namespace dmapper
} //namespace writerfilter

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


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: util.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include <stdlib.h>
#include <fstream>
#include <string>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/drawing/BitmapMode.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#include <com/sun/star/text/TextContentAnchorType.hpp>
#include <resourcemodel/WW8ResourceModel.hxx>

namespace writerfilter
{
using namespace com::sun::star;
using namespace std;
using text::TextContentAnchorType;
static string & logger_file()
{
    static string _logger_file = string(getenv("TEMP")?getenv("TEMP"):"/tmp") + "/writerfilter.ooxml.tmp";
    return _logger_file;
}

static ofstream & logger_stream()
{
    static ofstream _logger_stream(logger_file().c_str());
    return _logger_stream;
}

void logger(string prefix, string message)
{
    logger_stream() << prefix <<  ":" << message << endl;
    logger_stream().flush();
}

string propertysetToString(uno::Reference<beans::XPropertySet> const & xPropSet)
{
    string sResult;

    static int nAttribNames = 9;
    static string sPropertyAttribNames[9] =
        {
            "MAYBEVOID",
            "BOUND",
            "CONSTRAINED",
            "TRANSIENT",
            "READONLY",
            "MAYBEAMBIGUOUS",
            "MAYBEDEFAULT",
            "REMOVEABLE",
            "OPTIONAL"
        };

    uno::Reference<beans::XPropertySetInfo> xPropSetInfo
        (xPropSet->getPropertySetInfo());

    if (xPropSetInfo.is())
    {
        uno::Sequence<beans::Property> aProps(xPropSetInfo->getProperties());

        sResult +="<propertyset>";

        for (sal_Int32 n = 0; n < aProps.getLength(); n++)
        {
            ::rtl::OUString sPropName(aProps[n].Name);

            if (xPropSetInfo->hasPropertyByName(sPropName))
            {
                uno::Any aAny;
                try
                {
                    xPropSet->getPropertyValue(sPropName) >>= aAny;
                }
                catch (beans::UnknownPropertyException)
                {
                    sResult += "<unknown-property>";
                    sResult += OUStringToOString
                        (sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
                    sResult += "</unknown-property>";
                }

                if (aAny.hasValue())
                {
                    sResult += "<property name=\"";
                    sResult += OUStringToOString
                        (sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
                    sResult +="\" type=\"";

                    ::rtl::OUString sPropType(aProps[n].Type.getTypeName());
                    sResult += OUStringToOString
                        (sPropType, RTL_TEXTENCODING_ASCII_US).getStr();

                    sResult += "\" attribs=\"";

                    sal_uInt16 nMask = 1;
                    bool bFirstAttrib = true;
                    sal_uInt16 nAttribs = aProps[n].Attributes;
                    for (int i = 0; i < nAttribNames; i++)
                    {
                        if ((nAttribs & nMask) != 0)
                        {
                            if (bFirstAttrib)
                                bFirstAttrib = false;
                            else
                                sResult += "|";

                            sResult += sPropertyAttribNames[i];
                        }

                        nMask <<= 1;
                    }

                    sResult += "\">";

                    char buffer[256];
                    if (sPropType ==
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                        ("byte")))
                    {
                        sal_Int8 nValue = 0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%d", nValue);
                        sResult += buffer;
                    }
                    if (sPropType ==
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                        ("short")))
                    {
                        sal_Int16 nValue = 0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%d", nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("long")))
                    {
                        sal_Int32 nValue = 0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%" SAL_PRIdINT32, nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("float")))
                    {
                        float nValue = 0.0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%f", nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("double")))
                    {
                        double nValue = 0.0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%lf", nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("boolean")))
                    {
                        sal_Bool nValue = sal_False;
                        aAny >>= nValue;

                        if (nValue)
                            sResult += "true";
                        else
                            sResult += "false";
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("string")))
                    {
                        ::rtl::OUString sValue;
                        aAny >>= sValue;

                        sResult += OUStringToOString
                            (sValue, RTL_TEXTENCODING_ASCII_US).getStr();
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.text.TextContentAnchorType")))
                    {
                        text::TextContentAnchorType nValue;
                        aAny >>= nValue;

                        switch (nValue)
                        {
                        case text::TextContentAnchorType_AT_PARAGRAPH:
                            sResult += "AT_PARAGRAPH";
                            break;
                        case text::TextContentAnchorType_AS_CHARACTER:
                            sResult += "AS_CHARACTER";
                            break;
                        case text::TextContentAnchorType_AT_PAGE:
                            sResult += "AT_PAGE";
                            break;
                        case text::TextContentAnchorType_AT_FRAME:
                            sResult += "AT_FRAME";
                            break;
                        case text::TextContentAnchorType_AT_CHARACTER:
                            sResult += "AT_CHARACTER";
                            break;
                        case text::TextContentAnchorType_MAKE_FIXED_SIZE:
                            sResult += "MAKE_FIXED_SIZE";
                            break;
                        default:
                            break;
                        }
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.awt.Point")))
                    {
                        awt::Point aPoint;
                        aAny >>= aPoint;

                        snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")", aPoint.X,
                                 aPoint.Y);

                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.awt.Rectangle")))
                    {
                        awt::Rectangle aRect;
                        aAny >>= aRect;

                        snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")",
                                 aRect.X, aRect.Y, aRect.Width, aRect.Height);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.drawing.FillStyle")))
                    {
                        drawing::FillStyle nValue;
                        aAny >>= nValue;

                        switch (nValue)
                        {
                        case drawing::FillStyle_NONE:
                            sResult += "NONE";
                            break;
                        case drawing::FillStyle_SOLID:
                            sResult += "SOLID";
                            break;
                        case drawing::FillStyle_GRADIENT:
                            sResult += "GRADIENT";
                            break;
                        case drawing::FillStyle_HATCH:
                            sResult += "HATCH";
                            break;
                        case drawing::FillStyle_BITMAP:
                            sResult += "BITMAP";
                            break;
                        case drawing::FillStyle_MAKE_FIXED_SIZE:
                            sResult += "MAKE_FIXED_SIZE";
                            break;
                        }
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.drawing.BitmapMode")))
                    {
                        drawing::BitmapMode nValue;
                        aAny >>= nValue;

                        switch (nValue)
                        {
                        case drawing::BitmapMode_REPEAT:
                            sResult += "REPEAT";
                            break;
                        case drawing::BitmapMode_STRETCH:
                            sResult += "STRETCH";
                            break;
                        case drawing::BitmapMode_NO_REPEAT:
                            sResult += "NO_REPEAT";
                            break;
                        case drawing::BitmapMode_MAKE_FIXED_SIZE:
                            sResult += "MAKE_FIXED_SIZE";
                            break;
                        }
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.drawing.HomogenMatrix3")))
                    {
                        drawing::HomogenMatrix3 aMatrix;
                        aAny >>= aMatrix;

                        snprintf(buffer, sizeof(buffer),
                                 "((%f %f %f)(%f %f %f)(%f %f %f))",
                                 aMatrix.Line1.Column1,
                                 aMatrix.Line1.Column2,
                                 aMatrix.Line1.Column3,
                                 aMatrix.Line2.Column1,
                                 aMatrix.Line2.Column2,
                                 aMatrix.Line2.Column3,
                                 aMatrix.Line3.Column1,
                                 aMatrix.Line3.Column2,
                                 aMatrix.Line3.Column3);
                        sResult += buffer;
                    }

                    sResult += "</property>";
                }
            }
        }
        sResult += "</propertyset>";
    }

    return sResult;
}
}
<commit_msg>INTEGRATION: CWS hr51 (1.3.10); FILE MERGED 2008/06/06 14:12:15 hr 1.3.10.1: #i88947#: includes<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: util.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <com/sun/star/awt/Point.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/drawing/BitmapMode.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include <com/sun/star/drawing/HomogenMatrix3.hpp>
#include <com/sun/star/text/TextContentAnchorType.hpp>
#include <resourcemodel/WW8ResourceModel.hxx>

namespace writerfilter
{
using namespace com::sun::star;
using namespace std;
using text::TextContentAnchorType;
static string & logger_file()
{
    static string _logger_file = string(getenv("TEMP")?getenv("TEMP"):"/tmp") + "/writerfilter.ooxml.tmp";
    return _logger_file;
}

static ofstream & logger_stream()
{
    static ofstream _logger_stream(logger_file().c_str());
    return _logger_stream;
}

void logger(string prefix, string message)
{
    logger_stream() << prefix <<  ":" << message << endl;
    logger_stream().flush();
}

string propertysetToString(uno::Reference<beans::XPropertySet> const & xPropSet)
{
    string sResult;

    static int nAttribNames = 9;
    static string sPropertyAttribNames[9] =
        {
            "MAYBEVOID",
            "BOUND",
            "CONSTRAINED",
            "TRANSIENT",
            "READONLY",
            "MAYBEAMBIGUOUS",
            "MAYBEDEFAULT",
            "REMOVEABLE",
            "OPTIONAL"
        };

    uno::Reference<beans::XPropertySetInfo> xPropSetInfo
        (xPropSet->getPropertySetInfo());

    if (xPropSetInfo.is())
    {
        uno::Sequence<beans::Property> aProps(xPropSetInfo->getProperties());

        sResult +="<propertyset>";

        for (sal_Int32 n = 0; n < aProps.getLength(); n++)
        {
            ::rtl::OUString sPropName(aProps[n].Name);

            if (xPropSetInfo->hasPropertyByName(sPropName))
            {
                uno::Any aAny;
                try
                {
                    xPropSet->getPropertyValue(sPropName) >>= aAny;
                }
                catch (beans::UnknownPropertyException)
                {
                    sResult += "<unknown-property>";
                    sResult += OUStringToOString
                        (sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
                    sResult += "</unknown-property>";
                }

                if (aAny.hasValue())
                {
                    sResult += "<property name=\"";
                    sResult += OUStringToOString
                        (sPropName, RTL_TEXTENCODING_ASCII_US).getStr();
                    sResult +="\" type=\"";

                    ::rtl::OUString sPropType(aProps[n].Type.getTypeName());
                    sResult += OUStringToOString
                        (sPropType, RTL_TEXTENCODING_ASCII_US).getStr();

                    sResult += "\" attribs=\"";

                    sal_uInt16 nMask = 1;
                    bool bFirstAttrib = true;
                    sal_uInt16 nAttribs = aProps[n].Attributes;
                    for (int i = 0; i < nAttribNames; i++)
                    {
                        if ((nAttribs & nMask) != 0)
                        {
                            if (bFirstAttrib)
                                bFirstAttrib = false;
                            else
                                sResult += "|";

                            sResult += sPropertyAttribNames[i];
                        }

                        nMask <<= 1;
                    }

                    sResult += "\">";

                    char buffer[256];
                    if (sPropType ==
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                        ("byte")))
                    {
                        sal_Int8 nValue = 0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%d", nValue);
                        sResult += buffer;
                    }
                    if (sPropType ==
                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                        ("short")))
                    {
                        sal_Int16 nValue = 0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%d", nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("long")))
                    {
                        sal_Int32 nValue = 0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%" SAL_PRIdINT32, nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("float")))
                    {
                        float nValue = 0.0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%f", nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("double")))
                    {
                        double nValue = 0.0;
                        aAny >>= nValue;

                        snprintf(buffer, sizeof(buffer), "%lf", nValue);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("boolean")))
                    {
                        sal_Bool nValue = sal_False;
                        aAny >>= nValue;

                        if (nValue)
                            sResult += "true";
                        else
                            sResult += "false";
                    }
                    else if (sPropType ==
                             ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
                                             ("string")))
                    {
                        ::rtl::OUString sValue;
                        aAny >>= sValue;

                        sResult += OUStringToOString
                            (sValue, RTL_TEXTENCODING_ASCII_US).getStr();
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.text.TextContentAnchorType")))
                    {
                        text::TextContentAnchorType nValue;
                        aAny >>= nValue;

                        switch (nValue)
                        {
                        case text::TextContentAnchorType_AT_PARAGRAPH:
                            sResult += "AT_PARAGRAPH";
                            break;
                        case text::TextContentAnchorType_AS_CHARACTER:
                            sResult += "AS_CHARACTER";
                            break;
                        case text::TextContentAnchorType_AT_PAGE:
                            sResult += "AT_PAGE";
                            break;
                        case text::TextContentAnchorType_AT_FRAME:
                            sResult += "AT_FRAME";
                            break;
                        case text::TextContentAnchorType_AT_CHARACTER:
                            sResult += "AT_CHARACTER";
                            break;
                        case text::TextContentAnchorType_MAKE_FIXED_SIZE:
                            sResult += "MAKE_FIXED_SIZE";
                            break;
                        default:
                            break;
                        }
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.awt.Point")))
                    {
                        awt::Point aPoint;
                        aAny >>= aPoint;

                        snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")", aPoint.X,
                                 aPoint.Y);

                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.awt.Rectangle")))
                    {
                        awt::Rectangle aRect;
                        aAny >>= aRect;

                        snprintf(buffer, sizeof(buffer), "(%" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ", %" SAL_PRIdINT32 ")",
                                 aRect.X, aRect.Y, aRect.Width, aRect.Height);
                        sResult += buffer;
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.drawing.FillStyle")))
                    {
                        drawing::FillStyle nValue;
                        aAny >>= nValue;

                        switch (nValue)
                        {
                        case drawing::FillStyle_NONE:
                            sResult += "NONE";
                            break;
                        case drawing::FillStyle_SOLID:
                            sResult += "SOLID";
                            break;
                        case drawing::FillStyle_GRADIENT:
                            sResult += "GRADIENT";
                            break;
                        case drawing::FillStyle_HATCH:
                            sResult += "HATCH";
                            break;
                        case drawing::FillStyle_BITMAP:
                            sResult += "BITMAP";
                            break;
                        case drawing::FillStyle_MAKE_FIXED_SIZE:
                            sResult += "MAKE_FIXED_SIZE";
                            break;
                        }
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.drawing.BitmapMode")))
                    {
                        drawing::BitmapMode nValue;
                        aAny >>= nValue;

                        switch (nValue)
                        {
                        case drawing::BitmapMode_REPEAT:
                            sResult += "REPEAT";
                            break;
                        case drawing::BitmapMode_STRETCH:
                            sResult += "STRETCH";
                            break;
                        case drawing::BitmapMode_NO_REPEAT:
                            sResult += "NO_REPEAT";
                            break;
                        case drawing::BitmapMode_MAKE_FIXED_SIZE:
                            sResult += "MAKE_FIXED_SIZE";
                            break;
                        }
                    }
                    else if (sPropType ==
                             ::rtl::OUString
                             (RTL_CONSTASCII_USTRINGPARAM
                              ("com.sun.star.drawing.HomogenMatrix3")))
                    {
                        drawing::HomogenMatrix3 aMatrix;
                        aAny >>= aMatrix;

                        snprintf(buffer, sizeof(buffer),
                                 "((%f %f %f)(%f %f %f)(%f %f %f))",
                                 aMatrix.Line1.Column1,
                                 aMatrix.Line1.Column2,
                                 aMatrix.Line1.Column3,
                                 aMatrix.Line2.Column1,
                                 aMatrix.Line2.Column2,
                                 aMatrix.Line2.Column3,
                                 aMatrix.Line3.Column1,
                                 aMatrix.Line3.Column2,
                                 aMatrix.Line3.Column3);
                        sResult += buffer;
                    }

                    sResult += "</property>";
                }
            }
        }
        sResult += "</propertyset>";
    }

    return sResult;
}
}
<|endoftext|>


<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_CONTAINER_HH__
#define __RAPICORN_CONTAINER_HH__

#include <ui/widget.hh>

namespace Rapicorn {

class ResizeContainerImpl;

// == FocusIndicator ==
class FocusIndicator : public virtual Aida::ImplicitBase {
public:
  virtual void  focusable_container_change (ContainerImpl&) = 0;
};

// == Container ==
struct ContainerImpl : public virtual WidgetImpl, public virtual ContainerIface {
  friend              class WidgetImpl;
  friend              class WindowImpl;
  void                uncross_descendant    (WidgetImpl          &descendant);
  size_t              widget_cross_link     (WidgetImpl           &owner,
                                             WidgetImpl           &link,
                                             const WidgetSlot &uncross);
  void                widget_cross_unlink   (WidgetImpl           &owner,
                                             WidgetImpl           &link,
                                             size_t              link_id);
  void                widget_uncross_links  (WidgetImpl           &owner,
                                             WidgetImpl           &link);
  WidgetGroup*        retrieve_widget_group (const String &group_name, WidgetGroupType group_type, bool force_create);
protected:
  virtual            ~ContainerImpl     ();
  virtual void        do_changed        (const String &name) override;
  virtual void        add_child         (WidgetImpl           &widget) = 0;
  virtual void        repack_child      (WidgetImpl &widget, const PackInfo &orig, const PackInfo &pnew);
  virtual void        remove_child      (WidgetImpl           &widget) = 0;
  virtual void        unparent_child    (WidgetImpl           &widget);
  virtual void        dispose_widget    (WidgetImpl           &widget);
  virtual void        hierarchy_changed (WidgetImpl           *old_toplevel);
  virtual bool        move_focus        (FocusDir              fdir);
  void                expose_enclosure  (); /* expose without children */
  void                change_unviewable (WidgetImpl &child, bool);
  virtual void        focus_lost        ()                              { set_focus_child (NULL); }
  virtual void        set_focus_child   (WidgetImpl *widget);
  virtual void        scroll_to_child   (WidgetImpl &widget);
  virtual void        dump_test_data    (TestStream &tstream);
  static Allocation   layout_child      (WidgetImpl &child, const Allocation &carea);
  static Requisition  size_request_child (WidgetImpl &child, bool *hspread, bool *vspread);
public:
  virtual WidgetImplP*  begin             () const = 0;
  virtual WidgetImplP*  end               () const = 0;
  WidgetImpl*  get_focus_child            () const;
  void         register_focus_indicator   (FocusIndicator&);
  void         unregister_focus_indicator (FocusIndicator&);
  virtual void foreach_recursive          (const std::function<void (WidgetImpl&)> &f) override;
  void                  child_container (ContainerImpl  *child_container);
  ContainerImpl&        child_container ();
  virtual size_t        n_children      () = 0;
  virtual WidgetImpl*   nth_child       (size_t nth) = 0;
  bool                  has_children    ()                              { return 0 != n_children(); }
  bool                  remove          (WidgetImpl           &widget);
  bool                  remove          (WidgetImpl           *widget)  { assert_return (widget != NULL, 0); return remove (*widget); }
  void                  add             (WidgetImpl                   &widget);
  void                  add             (WidgetImpl                   *widget);
  virtual Affine        child_affine    (const WidgetImpl             &widget); /* container => widget affine */
  virtual void          point_children  (Point                   p, /* widget coordinates relative */
                                         std::vector<WidgetImplP>     &stack);
  void    display_window_point_children (Point                   p, /* display_window coordinates relative */
                                         std::vector<WidgetImplP>     &stack);
  virtual ContainerImpl* as_container_impl ()                           { return this; }
  virtual void          render_recursive(RenderContext &rcontext);
  void                  debug_tree      (String indent = String());
  // ContainerIface
  virtual WidgetIfaceP create_widget    (const String &widget_identifier, const StringSeq &args) override;
  virtual void         remove_widget    (WidgetIface &child) override;
};

// == Single Child Container ==
class SingleContainerImpl : public virtual ContainerImpl {
  WidgetImplP           child_widget;
protected:
  virtual void          size_request            (Requisition &requisition);
  virtual void          size_allocate           (Allocation area, bool changed);
  virtual void          render                  (RenderContext&, const Rect&) {}
  WidgetImpl&           get_child               () { critical_unless (child_widget != NULL); return *child_widget; }
  virtual              ~SingleContainerImpl     ();
  virtual WidgetImplP*  begin                   () const override;
  virtual WidgetImplP*  end                     () const override;
  virtual size_t        n_children              () { return child_widget ? 1 : 0; }
  virtual WidgetImpl*   nth_child               (size_t nth) { return nth == 0 ? child_widget.get() : NULL; }
  bool                  has_visible_child       () { return child_widget && child_widget->visible(); }
  bool                  has_drawable_child      () { return child_widget && child_widget->drawable(); }
  virtual void          add_child               (WidgetImpl   &widget);
  virtual void          remove_child            (WidgetImpl   &widget);
  explicit              SingleContainerImpl     ();
};

// == AnchorInfo ==
struct AnchorInfo {
  ResizeContainerImpl *resize_container;
  ViewportImpl        *viewport;
  WindowImpl          *window;
  constexpr AnchorInfo() : resize_container (NULL), viewport (NULL), window (NULL) {}
};

// == Resize Container ==
class ResizeContainerImpl : public virtual SingleContainerImpl {
  uint                  tunable_requisition_counter_;
  uint                  resizer_;
  AnchorInfo            anchor_info_;
  void                  idle_sizing             ();
  void                  update_anchor_info      ();
protected:
  virtual void          invalidate_parent       ();
  virtual void          hierarchy_changed       (WidgetImpl *old_toplevel);
  void                  negotiate_size          (const Allocation *carea);
  explicit              ResizeContainerImpl     ();
  virtual              ~ResizeContainerImpl     ();
public:
  bool                  requisitions_tunable    () const { return tunable_requisition_counter_ > 0; }
  AnchorInfo*           container_anchor_info   () { return &anchor_info_; }
};

// == Multi Child Container ==
class MultiContainerImpl : public virtual ContainerImpl {
  std::vector<WidgetImplP> widgets;
protected:
  virtual              ~MultiContainerImpl      ();
  virtual void          render                  (RenderContext&, const Rect&) {}
  virtual WidgetImplP*  begin                   () const override;
  virtual WidgetImplP*  end                     () const override;
  virtual size_t        n_children              () { return widgets.size(); }
  virtual WidgetImpl*   nth_child               (size_t nth) { return nth < widgets.size() ? widgets[nth].get() : NULL; }
  virtual void          add_child               (WidgetImpl   &widget);
  virtual void          remove_child            (WidgetImpl   &widget);
  void                  raise_child             (WidgetImpl   &widget);
  void                  lower_child             (WidgetImpl   &widget);
  void                  remove_all_children     ();
  explicit              MultiContainerImpl      ();
};

} // Rapicorn

#endif  /* __RAPICORN_CONTAINER_HH__ */
<commit_msg>UI: sort out MultiContainerImpl public methods<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_CONTAINER_HH__
#define __RAPICORN_CONTAINER_HH__

#include <ui/widget.hh>

namespace Rapicorn {

class ResizeContainerImpl;

// == FocusIndicator ==
class FocusIndicator : public virtual Aida::ImplicitBase {
public:
  virtual void  focusable_container_change (ContainerImpl&) = 0;
};

// == Container ==
struct ContainerImpl : public virtual WidgetImpl, public virtual ContainerIface {
  friend              class WidgetImpl;
  friend              class WindowImpl;
  void                uncross_descendant    (WidgetImpl          &descendant);
  size_t              widget_cross_link     (WidgetImpl           &owner,
                                             WidgetImpl           &link,
                                             const WidgetSlot &uncross);
  void                widget_cross_unlink   (WidgetImpl           &owner,
                                             WidgetImpl           &link,
                                             size_t              link_id);
  void                widget_uncross_links  (WidgetImpl           &owner,
                                             WidgetImpl           &link);
  WidgetGroup*        retrieve_widget_group (const String &group_name, WidgetGroupType group_type, bool force_create);
protected:
  virtual            ~ContainerImpl     ();
  virtual void        do_changed        (const String &name) override;
  virtual void        add_child         (WidgetImpl           &widget) = 0;
  virtual void        repack_child      (WidgetImpl &widget, const PackInfo &orig, const PackInfo &pnew);
  virtual void        remove_child      (WidgetImpl           &widget) = 0;
  virtual void        unparent_child    (WidgetImpl           &widget);
  virtual void        dispose_widget    (WidgetImpl           &widget);
  virtual void        hierarchy_changed (WidgetImpl           *old_toplevel);
  virtual bool        move_focus        (FocusDir              fdir);
  void                expose_enclosure  (); /* expose without children */
  void                change_unviewable (WidgetImpl &child, bool);
  virtual void        focus_lost        ()                              { set_focus_child (NULL); }
  virtual void        set_focus_child   (WidgetImpl *widget);
  virtual void        scroll_to_child   (WidgetImpl &widget);
  virtual void        dump_test_data    (TestStream &tstream);
  static Allocation   layout_child      (WidgetImpl &child, const Allocation &carea);
  static Requisition  size_request_child (WidgetImpl &child, bool *hspread, bool *vspread);
public:
  virtual WidgetImplP*  begin             () const = 0;
  virtual WidgetImplP*  end               () const = 0;
  WidgetImpl*  get_focus_child            () const;
  void         register_focus_indicator   (FocusIndicator&);
  void         unregister_focus_indicator (FocusIndicator&);
  virtual void foreach_recursive          (const std::function<void (WidgetImpl&)> &f) override;
  void                  child_container (ContainerImpl  *child_container);
  ContainerImpl&        child_container ();
  virtual size_t        n_children      () = 0;
  virtual WidgetImpl*   nth_child       (size_t nth) = 0;
  bool                  has_children    ()                              { return 0 != n_children(); }
  bool                  remove          (WidgetImpl           &widget);
  bool                  remove          (WidgetImpl           *widget)  { assert_return (widget != NULL, 0); return remove (*widget); }
  void                  add             (WidgetImpl                   &widget);
  void                  add             (WidgetImpl                   *widget);
  virtual Affine        child_affine    (const WidgetImpl             &widget); /* container => widget affine */
  virtual void          point_children  (Point                   p, /* widget coordinates relative */
                                         std::vector<WidgetImplP>     &stack);
  void    display_window_point_children (Point                   p, /* display_window coordinates relative */
                                         std::vector<WidgetImplP>     &stack);
  virtual ContainerImpl* as_container_impl ()                           { return this; }
  virtual void          render_recursive(RenderContext &rcontext);
  void                  debug_tree      (String indent = String());
  // ContainerIface
  virtual WidgetIfaceP create_widget    (const String &widget_identifier, const StringSeq &args) override;
  virtual void         remove_widget    (WidgetIface &child) override;
};

// == Single Child Container ==
class SingleContainerImpl : public virtual ContainerImpl {
  WidgetImplP           child_widget;
protected:
  virtual void          size_request            (Requisition &requisition);
  virtual void          size_allocate           (Allocation area, bool changed);
  virtual void          render                  (RenderContext&, const Rect&) {}
  WidgetImpl&           get_child               () { critical_unless (child_widget != NULL); return *child_widget; }
  virtual              ~SingleContainerImpl     ();
  virtual WidgetImplP*  begin                   () const override;
  virtual WidgetImplP*  end                     () const override;
  virtual size_t        n_children              () { return child_widget ? 1 : 0; }
  virtual WidgetImpl*   nth_child               (size_t nth) { return nth == 0 ? child_widget.get() : NULL; }
  bool                  has_visible_child       () { return child_widget && child_widget->visible(); }
  bool                  has_drawable_child      () { return child_widget && child_widget->drawable(); }
  virtual void          add_child               (WidgetImpl   &widget);
  virtual void          remove_child            (WidgetImpl   &widget);
  explicit              SingleContainerImpl     ();
};

// == AnchorInfo ==
struct AnchorInfo {
  ResizeContainerImpl *resize_container;
  ViewportImpl        *viewport;
  WindowImpl          *window;
  constexpr AnchorInfo() : resize_container (NULL), viewport (NULL), window (NULL) {}
};

// == Resize Container ==
class ResizeContainerImpl : public virtual SingleContainerImpl {
  uint                  tunable_requisition_counter_;
  uint                  resizer_;
  AnchorInfo            anchor_info_;
  void                  idle_sizing             ();
  void                  update_anchor_info      ();
protected:
  virtual void          invalidate_parent       ();
  virtual void          hierarchy_changed       (WidgetImpl *old_toplevel);
  void                  negotiate_size          (const Allocation *carea);
  explicit              ResizeContainerImpl     ();
  virtual              ~ResizeContainerImpl     ();
public:
  bool                  requisitions_tunable    () const { return tunable_requisition_counter_ > 0; }
  AnchorInfo*           container_anchor_info   () { return &anchor_info_; }
};

// == Multi Child Container ==
class MultiContainerImpl : public virtual ContainerImpl {
  std::vector<WidgetImplP> widgets;
protected:
  virtual              ~MultiContainerImpl      ();
  virtual void          render                  (RenderContext&, const Rect&) override {}
  virtual void          add_child               (WidgetImpl   &widget) override;
  virtual void          remove_child            (WidgetImpl   &widget) override;
  explicit              MultiContainerImpl      ();
public:
  virtual WidgetImplP*  begin                   () const override;
  virtual WidgetImplP*  end                     () const override;
  virtual size_t        n_children              () override           { return widgets.size(); }
  virtual WidgetImpl*   nth_child               (size_t nth) override { return nth < widgets.size() ? widgets[nth].get() : NULL; }
  void                  raise_child             (WidgetImpl   &widget);
  void                  lower_child             (WidgetImpl   &widget);
  void                  remove_all_children     ();
};

} // Rapicorn

#endif  /* __RAPICORN_CONTAINER_HH__ */
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gameprojectprivate.h"

#include "savable.h"
#include "achievement.h"

#include <core/gluonobject.h>
#include <core/debughelper.h>

#include <QtCore/QStringList>
#include <QtCore/QDir>

using namespace GluonEngine;

GameProjectPrivate::GameProjectPrivate()
    : entryPoint( 0 )
    , icon( 0 )
    , screenshot( 0 )
    , userName( "user" )
{
}

GameProjectPrivate::GameProjectPrivate( const GameProjectPrivate& other )
    : QSharedData( other )
    , description( other.description )
    , homepage( other.homepage )
    , mediaInfo( other.mediaInfo )
    , filename( other.filename )
    , dirname( other.dirname )
    , entryPoint( other.entryPoint )
    , icon( other.icon )
    , screenshot( other.screenshot )
    , userName( other.userName )
{
}

GameProjectPrivate::~GameProjectPrivate()
{
}

bool
GameProjectPrivate::saveChildren( const GluonCore::GluonObject* parent )
{
    DEBUG_FUNC_NAME
    if( !parent )
    {
        DEBUG_TEXT( QString( "Object child was null!" ) )
        return false;
    }

    for( int i = 0; i < parent->children().size(); ++i )
    {
        GluonCore::GluonObject* child = parent->child( i );
        if( child && Savable::saveToFile( child ) )
        {
            DEBUG_TEXT2( "Saved object named %1", child->name() )
        }

        // Recurse!
        saveChildren( qobject_cast<const GluonCore::GluonObject*>( child ) );
    }
    return true;
}
<commit_msg>Engine: Debug--;<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gameprojectprivate.h"

#include "savable.h"
#include "achievement.h"

#include <core/gluonobject.h>
#include <core/debughelper.h>

#include <QtCore/QStringList>
#include <QtCore/QDir>

using namespace GluonEngine;

GameProjectPrivate::GameProjectPrivate()
    : entryPoint( 0 )
    , icon( 0 )
    , screenshot( 0 )
    , userName( "user" )
{
}

GameProjectPrivate::GameProjectPrivate( const GameProjectPrivate& other )
    : QSharedData( other )
    , description( other.description )
    , homepage( other.homepage )
    , mediaInfo( other.mediaInfo )
    , filename( other.filename )
    , dirname( other.dirname )
    , entryPoint( other.entryPoint )
    , icon( other.icon )
    , screenshot( other.screenshot )
    , userName( other.userName )
{
}

GameProjectPrivate::~GameProjectPrivate()
{
}

bool
GameProjectPrivate::saveChildren( const GluonCore::GluonObject* parent )
{
    if( !parent )
    {
        return false;
    }

    for( int i = 0; i < parent->children().size(); ++i )
    {
        GluonCore::GluonObject* child = parent->child( i );
        if( child )
            Savable::saveToFile( child );

        // Recurse!
        saveChildren( qobject_cast<const GluonCore::GluonObject*>( child ) );
    }
    return true;
}
<|endoftext|>