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

#include "app/l10n_util.h"
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"

const std::wstring DevToolsWindow::kDevToolsApp = L"DevToolsApp";

// static
TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) {
  if (!inspected_tab) {
    return NULL;
  }

  if (!DevToolsManager::GetInstance())
    return NULL;  // Happens only in tests.

  DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
          GetDevToolsClientHostFor(inspected_tab->render_view_host());
  if (!client_host) {
    return NULL;
  }

  DevToolsWindow* window = client_host->AsDevToolsWindow();
  if (!window || !window->is_docked()) {
    return NULL;
  }
  return window->tab_contents();
}

DevToolsWindow::DevToolsWindow(Profile* profile,
                               RenderViewHost* inspected_rvh,
                               bool docked)
    : profile_(profile),
      browser_(NULL),
      docked_(docked),
      is_loaded_(false),
      open_console_on_load_(false) {
  // Create TabContents with devtools.
  tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);
  tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI);
  tab_contents_->controller().LoadURL(GetDevToolsUrl(), GURL(), PageTransition::START_PAGE);

  // Wipe out page icon so that the default application icon is used.
  NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
  entry->favicon().set_bitmap(SkBitmap());
  entry->favicon().set_is_valid(true);

  // Register on-load actions.
  registrar_.Add(this,
                 NotificationType::LOAD_STOP,
                 Source<NavigationController>(&tab_contents_->controller()));
  registrar_.Add(this,
                 NotificationType::TAB_CLOSING,
                 Source<NavigationController>(&tab_contents_->controller()));
  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());
  inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents();
}

DevToolsWindow::~DevToolsWindow() {
}

DevToolsWindow* DevToolsWindow::AsDevToolsWindow() {
  return this;
}

void DevToolsWindow::SendMessageToClient(const IPC::Message& message) {
  RenderViewHost* target_host = tab_contents_->render_view_host();
  IPC::Message* m =  new IPC::Message(message);
  m->set_routing_id(target_host->routing_id());
  target_host->Send(m);
}

void DevToolsWindow::InspectedTabClosing() {
  if (docked_) {
    // Update dev tools to reflect removed dev tools window.

    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      inspected_window->UpdateDevTools();
    // In case of docked tab_contents we own it, so delete here.
    delete tab_contents_;

    delete this;
  } else {
    // First, initiate self-destruct to free all the registrars.
    // Then close all tabs. Browser will take care of deleting tab_contents
    // for us.
    Browser* browser = browser_;
    delete this;
    browser->CloseAllTabs();
  }
}

void DevToolsWindow::Show(bool open_console) {
  if (docked_) {
    // Just tell inspected browser to update splitter.
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window) {
      tab_contents_->set_delegate(this);
      inspected_window->UpdateDevTools();
      SetAttachedWindow();
      tab_contents_->view()->SetInitialFocus();
      if (open_console)
        ScheduleOpenConsole();
      return;
    } else {
      // Sometimes we don't know where to dock. Stay undocked.
      docked_ = false;
    }
  }

  if (!browser_)
    CreateDevToolsBrowser();

  browser_->window()->Show();
  SetAttachedWindow();
  tab_contents_->view()->SetInitialFocus();

  if (open_console)
    ScheduleOpenConsole();
}

void DevToolsWindow::Activate() {
  if (!docked_) {
    if (!browser_->window()->IsActive()) {
      browser_->window()->Activate();
    }
  } else {
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      tab_contents_->view()->Focus();
  }
}

void DevToolsWindow::SetDocked(bool docked) {
  if (docked_ == docked)
    return;
  if (docked && !GetInspectedBrowserWindow()) {
    // Cannot dock, avoid window flashing due to close-reopen cycle.
    return;
  }
  docked_ = docked;

  if (docked) {
    // Detach window from the external devtools browser. It will lead to
    // the browser object's close and delete. Remove observer first.
    TabStripModel* tabstrip_model = browser_->tabstrip_model();
    tabstrip_model->DetachTabContentsAt(
        tabstrip_model->GetIndexOfTabContents(tab_contents_));
    browser_ = NULL;
  } else {
    // Update inspected window to hide split and reset it.
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window) {
      inspected_window->UpdateDevTools();
      inspected_window = NULL;
    }
  }
  Show(false);
}

RenderViewHost* DevToolsWindow::GetRenderViewHost() {
  return tab_contents_->render_view_host();
}

void DevToolsWindow::CreateDevToolsBrowser() {
  // TODO(pfeldman): Make browser's getter for this key static.
  std::wstring wp_key = L"";
  wp_key.append(prefs::kBrowserWindowPlacement);
  wp_key.append(L"_");
  wp_key.append(kDevToolsApp);

  PrefService* prefs = g_browser_process->local_state();
  if (!prefs->FindPreference(wp_key.c_str())) {
    prefs->RegisterDictionaryPref(wp_key.c_str());
  }

  const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
  if (!wp_pref) {
    DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str());
    defaults->SetInteger(L"left", 100);
    defaults->SetInteger(L"top", 100);
    defaults->SetInteger(L"right", 740);
    defaults->SetInteger(L"bottom", 740);
    defaults->SetBoolean(L"maximized", false);
    defaults->SetBoolean(L"always_on_top", false);
  }

  browser_ = Browser::CreateForDevTools(profile_);
  browser_->tabstrip_model()->AddTabContents(
      tab_contents_, -1, false, PageTransition::START_PAGE, true);
}

BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
  for (BrowserList::const_iterator it = BrowserList::begin();
       it != BrowserList::end(); ++it) {
    Browser* browser = *it;
    for (int i = 0; i < browser->tab_count(); ++i) {
      TabContents* tab_contents = browser->GetTabContentsAt(i);
      if (tab_contents == inspected_tab_) {
        return browser->window();
      }
    }
  }
  return NULL;
}

void DevToolsWindow::SetAttachedWindow() {
  tab_contents_->render_view_host()->
      ExecuteJavascriptInWebFrame(
          L"", docked_ ? L"WebInspector.setAttachedWindow(true);" :
                         L"WebInspector.setAttachedWindow(false);");
}

void DevToolsWindow::Observe(NotificationType type,
                             const NotificationSource& source,
                             const NotificationDetails& details) {
  if (type == NotificationType::LOAD_STOP) {
    is_loaded_ = true;
    if (open_console_on_load_) {
      DoOpenConsole();
      open_console_on_load_ = false;
    }
  } else if (type == NotificationType::TAB_CLOSING) {
    if (Source<NavigationController>(source).ptr() ==
            &tab_contents_->controller()) {
      // This happens when browser closes all of its tabs as a result
      // of window.Close event.
      // Notify manager that this DevToolsClientHost no longer exists and
      // initiate self-destuct here.
      NotifyCloseListener();
      delete this;
    }
  } else if (type == NotificationType::BROWSER_THEME_CHANGED) {
    UpdateTheme();
  }
}

void DevToolsWindow::ScheduleOpenConsole() {
  if (is_loaded_)
    DoOpenConsole();
  else
    open_console_on_load_ = true;
}

void DevToolsWindow::DoOpenConsole() {
  tab_contents_->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();");
}

std::string SkColorToRGBAString(SkColor color) {
  // We convert the alpha using DoubleToString because StringPrintf will use
  // locale specific formatters (e.g., use , instead of . in German).
  return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color),
      SkColorGetG(color), SkColorGetB(color),
      DoubleToString(SkColorGetA(color) / 255.0).c_str());
}

GURL DevToolsWindow::GetDevToolsUrl() {
  BrowserThemeProvider* tp = profile_->GetThemeProvider();
  CHECK(tp);

  SkColor color_toolbar =
      tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
  SkColor color_tab_text =
      tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);

  std::string url_string = StringPrintf(
      "%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s",
      chrome::kChromeUIDevToolsURL,
      docked_ ? "true" : "false",
      SkColorToRGBAString(color_toolbar).c_str(),
      SkColorToRGBAString(color_tab_text).c_str());
  return GURL(url_string);
}

void DevToolsWindow::UpdateTheme() {
  BrowserThemeProvider* tp = profile_->GetThemeProvider();
  CHECK(tp);

  SkColor color_toolbar =
      tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
  SkColor color_tab_text =
      tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
  std::string command = StringPrintf(
      "WebInspector.setToolbarColors(\"%s\", \"%s\")",
      SkColorToRGBAString(color_toolbar).c_str(),
      SkColorToRGBAString(color_tab_text).c_str());
  tab_contents_->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command));
}

bool DevToolsWindow::PreHandleKeyboardEvent(
    const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
  if (docked_) {
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      return inspected_window->PreHandleKeyboardEvent(
          event, is_keyboard_shortcut);
  }
  return false;
}

void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
  if (docked_) {
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      inspected_window->HandleKeyboardEvent(event);
  }
}
<commit_msg>DevTools: keep manual docked state update until corresponding webkit change lands.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/l10n_util.h"
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"

const std::wstring DevToolsWindow::kDevToolsApp = L"DevToolsApp";

// static
TabContents* DevToolsWindow::GetDevToolsContents(TabContents* inspected_tab) {
  if (!inspected_tab) {
    return NULL;
  }

  if (!DevToolsManager::GetInstance())
    return NULL;  // Happens only in tests.

  DevToolsClientHost* client_host = DevToolsManager::GetInstance()->
          GetDevToolsClientHostFor(inspected_tab->render_view_host());
  if (!client_host) {
    return NULL;
  }

  DevToolsWindow* window = client_host->AsDevToolsWindow();
  if (!window || !window->is_docked()) {
    return NULL;
  }
  return window->tab_contents();
}

DevToolsWindow::DevToolsWindow(Profile* profile,
                               RenderViewHost* inspected_rvh,
                               bool docked)
    : profile_(profile),
      browser_(NULL),
      docked_(docked),
      is_loaded_(false),
      open_console_on_load_(false) {
  // Create TabContents with devtools.
  tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);
  tab_contents_->render_view_host()->AllowBindings(BindingsPolicy::DOM_UI);
  tab_contents_->controller().LoadURL(GetDevToolsUrl(), GURL(), PageTransition::START_PAGE);

  // Wipe out page icon so that the default application icon is used.
  NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
  entry->favicon().set_bitmap(SkBitmap());
  entry->favicon().set_is_valid(true);

  // Register on-load actions.
  registrar_.Add(this,
                 NotificationType::LOAD_STOP,
                 Source<NavigationController>(&tab_contents_->controller()));
  registrar_.Add(this,
                 NotificationType::TAB_CLOSING,
                 Source<NavigationController>(&tab_contents_->controller()));
  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());
  inspected_tab_ = inspected_rvh->delegate()->GetAsTabContents();
}

DevToolsWindow::~DevToolsWindow() {
}

DevToolsWindow* DevToolsWindow::AsDevToolsWindow() {
  return this;
}

void DevToolsWindow::SendMessageToClient(const IPC::Message& message) {
  RenderViewHost* target_host = tab_contents_->render_view_host();
  IPC::Message* m =  new IPC::Message(message);
  m->set_routing_id(target_host->routing_id());
  target_host->Send(m);
}

void DevToolsWindow::InspectedTabClosing() {
  if (docked_) {
    // Update dev tools to reflect removed dev tools window.

    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      inspected_window->UpdateDevTools();
    // In case of docked tab_contents we own it, so delete here.
    delete tab_contents_;

    delete this;
  } else {
    // First, initiate self-destruct to free all the registrars.
    // Then close all tabs. Browser will take care of deleting tab_contents
    // for us.
    Browser* browser = browser_;
    delete this;
    browser->CloseAllTabs();
  }
}

void DevToolsWindow::Show(bool open_console) {
  if (docked_) {
    // Just tell inspected browser to update splitter.
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window) {
      tab_contents_->set_delegate(this);
      inspected_window->UpdateDevTools();
      SetAttachedWindow();
      tab_contents_->view()->SetInitialFocus();
      if (open_console)
        ScheduleOpenConsole();
      return;
    } else {
      // Sometimes we don't know where to dock. Stay undocked.
      docked_ = false;
    }
  }

  if (!browser_)
    CreateDevToolsBrowser();

  browser_->window()->Show();
  SetAttachedWindow();
  tab_contents_->view()->SetInitialFocus();

  if (open_console)
    ScheduleOpenConsole();
}

void DevToolsWindow::Activate() {
  if (!docked_) {
    if (!browser_->window()->IsActive()) {
      browser_->window()->Activate();
    }
  } else {
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      tab_contents_->view()->Focus();
  }
}

void DevToolsWindow::SetDocked(bool docked) {
  if (docked_ == docked)
    return;
  if (docked && !GetInspectedBrowserWindow()) {
    // Cannot dock, avoid window flashing due to close-reopen cycle.
    return;
  }
  docked_ = docked;

  if (docked) {
    // Detach window from the external devtools browser. It will lead to
    // the browser object's close and delete. Remove observer first.
    TabStripModel* tabstrip_model = browser_->tabstrip_model();
    tabstrip_model->DetachTabContentsAt(
        tabstrip_model->GetIndexOfTabContents(tab_contents_));
    browser_ = NULL;
  } else {
    // Update inspected window to hide split and reset it.
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window) {
      inspected_window->UpdateDevTools();
      inspected_window = NULL;
    }
  }
  Show(false);
}

RenderViewHost* DevToolsWindow::GetRenderViewHost() {
  return tab_contents_->render_view_host();
}

void DevToolsWindow::CreateDevToolsBrowser() {
  // TODO(pfeldman): Make browser's getter for this key static.
  std::wstring wp_key = L"";
  wp_key.append(prefs::kBrowserWindowPlacement);
  wp_key.append(L"_");
  wp_key.append(kDevToolsApp);

  PrefService* prefs = g_browser_process->local_state();
  if (!prefs->FindPreference(wp_key.c_str())) {
    prefs->RegisterDictionaryPref(wp_key.c_str());
  }

  const DictionaryValue* wp_pref = prefs->GetDictionary(wp_key.c_str());
  if (!wp_pref) {
    DictionaryValue* defaults = prefs->GetMutableDictionary(wp_key.c_str());
    defaults->SetInteger(L"left", 100);
    defaults->SetInteger(L"top", 100);
    defaults->SetInteger(L"right", 740);
    defaults->SetInteger(L"bottom", 740);
    defaults->SetBoolean(L"maximized", false);
    defaults->SetBoolean(L"always_on_top", false);
  }

  browser_ = Browser::CreateForDevTools(profile_);
  browser_->tabstrip_model()->AddTabContents(
      tab_contents_, -1, false, PageTransition::START_PAGE, true);
}

BrowserWindow* DevToolsWindow::GetInspectedBrowserWindow() {
  for (BrowserList::const_iterator it = BrowserList::begin();
       it != BrowserList::end(); ++it) {
    Browser* browser = *it;
    for (int i = 0; i < browser->tab_count(); ++i) {
      TabContents* tab_contents = browser->GetTabContentsAt(i);
      if (tab_contents == inspected_tab_) {
        return browser->window();
      }
    }
  }
  return NULL;
}

void DevToolsWindow::SetAttachedWindow() {
  tab_contents_->render_view_host()->
      ExecuteJavascriptInWebFrame(
          L"", docked_ ? L"WebInspector.setAttachedWindow(true);" :
                         L"WebInspector.setAttachedWindow(false);");
}

void DevToolsWindow::Observe(NotificationType type,
                             const NotificationSource& source,
                             const NotificationDetails& details) {
  if (type == NotificationType::LOAD_STOP) {
    SetAttachedWindow();
    is_loaded_ = true;
    UpdateTheme();
    if (open_console_on_load_) {
      DoOpenConsole();
      open_console_on_load_ = false;
    }
  } else if (type == NotificationType::TAB_CLOSING) {
    if (Source<NavigationController>(source).ptr() ==
            &tab_contents_->controller()) {
      // This happens when browser closes all of its tabs as a result
      // of window.Close event.
      // Notify manager that this DevToolsClientHost no longer exists and
      // initiate self-destuct here.
      NotifyCloseListener();
      delete this;
    }
  } else if (type == NotificationType::BROWSER_THEME_CHANGED) {
    UpdateTheme();
  }
}

void DevToolsWindow::ScheduleOpenConsole() {
  if (is_loaded_)
    DoOpenConsole();
  else
    open_console_on_load_ = true;
}

void DevToolsWindow::DoOpenConsole() {
  tab_contents_->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", L"WebInspector.showConsole();");
}

std::string SkColorToRGBAString(SkColor color) {
  // We convert the alpha using DoubleToString because StringPrintf will use
  // locale specific formatters (e.g., use , instead of . in German).
  return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color),
      SkColorGetG(color), SkColorGetB(color),
      DoubleToString(SkColorGetA(color) / 255.0).c_str());
}

GURL DevToolsWindow::GetDevToolsUrl() {
  BrowserThemeProvider* tp = profile_->GetThemeProvider();
  CHECK(tp);

  SkColor color_toolbar =
      tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
  SkColor color_tab_text =
      tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);

  std::string url_string = StringPrintf(
      "%sdevtools.html?docked=%s&toolbar_color=%s&text_color=%s",
      chrome::kChromeUIDevToolsURL,
      docked_ ? "true" : "false",
      SkColorToRGBAString(color_toolbar).c_str(),
      SkColorToRGBAString(color_tab_text).c_str());
  return GURL(url_string);
}

void DevToolsWindow::UpdateTheme() {
  BrowserThemeProvider* tp = profile_->GetThemeProvider();
  CHECK(tp);

  SkColor color_toolbar =
      tp->GetColor(BrowserThemeProvider::COLOR_TOOLBAR);
  SkColor color_tab_text =
      tp->GetColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
  std::string command = StringPrintf(
      "WebInspector.setToolbarColors(\"%s\", \"%s\")",
      SkColorToRGBAString(color_toolbar).c_str(),
      SkColorToRGBAString(color_tab_text).c_str());
  tab_contents_->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", UTF8ToWide(command));
}

bool DevToolsWindow::PreHandleKeyboardEvent(
    const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) {
  if (docked_) {
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      return inspected_window->PreHandleKeyboardEvent(
          event, is_keyboard_shortcut);
  }
  return false;
}

void DevToolsWindow::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
  if (docked_) {
    BrowserWindow* inspected_window = GetInspectedBrowserWindow();
    if (inspected_window)
      inspected_window->HandleKeyboardEvent(event);
  }
}
<|endoftext|>


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

#include "chrome/test/ui/ui_test.h"

#include "base/file_path.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/testing_pref_service.h"

class NewTabUITest : public UITest {
 public:
  NewTabUITest() {
    dom_automation_enabled_ = true;
    // Set home page to the empty string so that we can set the home page using
    // preferences.
    homepage_ = "";

    // Setup the DEFAULT_THEME profile (has fake history entries).
    set_template_user_data(UITest::ComputeTypicalUserDataSource(
        UITest::DEFAULT_THEME));
  }
};

// Fails on XP, Linux: http://crbug.com/51721
TEST_F(NewTabUITest, FLAKY_NTPHasThumbnails) {
  // Switch to the "new tab" tab, which should be any new tab after the
  // first (the first is about:blank).
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(window.get());

  // Bring up a new tab page.
  ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
  int load_time;
  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));

  // Blank thumbnails on the NTP have the class 'filler' applied to the div.
  // If all the thumbnails load, there should be no div's with 'filler'.
  scoped_refptr<TabProxy> tab = window->GetActiveTab();
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"",
      L"window.domAutomationController.send("
      L"document.getElementsByClassName('filler').length == 0)",
      action_max_timeout_ms()));
}

// Fails about ~5% of the time on all platforms. http://crbug.com/45001
TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(window.get());

  // Go to the "new tab page" using its old url, rather than chrome://newtab.
  scoped_refptr<TabProxy> tab = window->GetTab(0);
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:")));
  int load_time;
  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));

  // Ensure there are some thumbnails loaded in the page.
  int thumbnails_count = -1;
  ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
      L"window.domAutomationController.send("
      L"document.getElementsByClassName('thumbnail-container').length)",
      &thumbnails_count));
  EXPECT_GT(thumbnails_count, 0);
}

TEST_F(NewTabUITest, UpdateUserPrefsVersion) {
  // PrefService with JSON user-pref file only, no enforced or advised prefs.
  scoped_ptr<PrefService> prefs(new TestingPrefService);

  // Does the migration
  NewTabUI::RegisterUserPrefs(prefs.get());

  ASSERT_EQ(NewTabUI::current_pref_version(),
            prefs->GetInteger(prefs::kNTPPrefVersion));

  // Reset the version
  prefs->ClearPref(prefs::kNTPPrefVersion);
  ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));

  bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
  ASSERT_TRUE(migrated);
  ASSERT_EQ(NewTabUI::current_pref_version(),
            prefs->GetInteger(prefs::kNTPPrefVersion));

  migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
  ASSERT_FALSE(migrated);
}
<commit_msg>Mark NewTabUITest.UpdateUserPrefsVersion as flaky.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

#include "base/file_path.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/pref_value_store.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/testing_pref_service.h"

class NewTabUITest : public UITest {
 public:
  NewTabUITest() {
    dom_automation_enabled_ = true;
    // Set home page to the empty string so that we can set the home page using
    // preferences.
    homepage_ = "";

    // Setup the DEFAULT_THEME profile (has fake history entries).
    set_template_user_data(UITest::ComputeTypicalUserDataSource(
        UITest::DEFAULT_THEME));
  }
};

// Fails on XP, Linux: http://crbug.com/51721
TEST_F(NewTabUITest, FLAKY_NTPHasThumbnails) {
  // Switch to the "new tab" tab, which should be any new tab after the
  // first (the first is about:blank).
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(window.get());

  // Bring up a new tab page.
  ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));
  int load_time;
  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));

  // Blank thumbnails on the NTP have the class 'filler' applied to the div.
  // If all the thumbnails load, there should be no div's with 'filler'.
  scoped_refptr<TabProxy> tab = window->GetActiveTab();
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"",
      L"window.domAutomationController.send("
      L"document.getElementsByClassName('filler').length == 0)",
      action_max_timeout_ms()));
}

// Fails about ~5% of the time on all platforms. http://crbug.com/45001
TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {
  scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(window.get());

  // Go to the "new tab page" using its old url, rather than chrome://newtab.
  scoped_refptr<TabProxy> tab = window->GetTab(0);
  ASSERT_TRUE(tab.get());
  ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:")));
  int load_time;
  ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));

  // Ensure there are some thumbnails loaded in the page.
  int thumbnails_count = -1;
  ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
      L"window.domAutomationController.send("
      L"document.getElementsByClassName('thumbnail-container').length)",
      &thumbnails_count));
  EXPECT_GT(thumbnails_count, 0);
}

// Flaky on XP bots: http://crbug.com/51726
TEST_F(NewTabUITest, FLAKY_UpdateUserPrefsVersion) {
  // PrefService with JSON user-pref file only, no enforced or advised prefs.
  scoped_ptr<PrefService> prefs(new TestingPrefService);

  // Does the migration
  NewTabUI::RegisterUserPrefs(prefs.get());

  ASSERT_EQ(NewTabUI::current_pref_version(),
            prefs->GetInteger(prefs::kNTPPrefVersion));

  // Reset the version
  prefs->ClearPref(prefs::kNTPPrefVersion);
  ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));

  bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
  ASSERT_TRUE(migrated);
  ASSERT_EQ(NewTabUI::current_pref_version(),
            prefs->GetInteger(prefs::kNTPPrefVersion));

  migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());
  ASSERT_FALSE(migrated);
}
<|endoftext|>


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

#include "chrome/test/ui/ui_test.h"

#include "app/sql/connection.h"
#include "app/sql/statement.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class MultipartResponseUITest : public UITest {
};

// http://crbug.com/50060
#if defined(OS_MACOSX)
#define MAYBE_SingleVisit DISABLED_SingleVisit
#else
#define MAYBE_SingleVisit SingleVisit
#endif

#if defined(NDEBUG)
// http://code.google.com/p/chromium/issues/detail?id=37746
// Running this test only for release builds as it fails in debug test
// runs
TEST_F(MultipartResponseUITest, SingleVisit) {
  // Make sure that visiting a multipart/x-mixed-replace site only
  // creates one entry in the visits table.
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab_proxy(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  NavigateToURL(server->TestServerPage("multipart"));
  std::wstring title;
  EXPECT_TRUE(tab_proxy->GetTabTitle(&title));
  EXPECT_EQ(L"page 9", title);
  CloseBrowserAndServer();

  // The browser has shutdown now.  Check the contents of the history
  // table.  We should have only one visit for the URL even though it
  // had 10 parts.
  sql::Connection db;
  FilePath history =
      user_data_dir().AppendASCII("Default").AppendASCII("History");
  ASSERT_TRUE(file_util::PathExists(history));
  ASSERT_TRUE(db.Open(history));
  std::string query(
      "SELECT COUNT(1) FROM visits, urls WHERE visits.url = urls.id"
      " AND urls.url LIKE 'http://localhost:%/multipart'");
  {
    sql::Statement statement(db.GetUniqueStatement(query.c_str()));
    EXPECT_TRUE(statement);
    EXPECT_TRUE(statement.Step());
    EXPECT_EQ(1, statement.ColumnInt(0));
  }
  db.Close();
}
#endif

}  // namespace
<commit_msg>Fix a typo in previous attempt at disabling a test.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

#include "app/sql/connection.h"
#include "app/sql/statement.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class MultipartResponseUITest : public UITest {
};

// http://crbug.com/50060
#if defined(OS_MACOSX)
#define MAYBE_SingleVisit DISABLED_SingleVisit
#else
#define MAYBE_SingleVisit SingleVisit
#endif

#if defined(NDEBUG)
// http://code.google.com/p/chromium/issues/detail?id=37746
// Running this test only for release builds as it fails in debug test
// runs
TEST_F(MultipartResponseUITest, MAYBE_SingleVisit) {
  // Make sure that visiting a multipart/x-mixed-replace site only
  // creates one entry in the visits table.
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab_proxy(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  NavigateToURL(server->TestServerPage("multipart"));
  std::wstring title;
  EXPECT_TRUE(tab_proxy->GetTabTitle(&title));
  EXPECT_EQ(L"page 9", title);
  CloseBrowserAndServer();

  // The browser has shutdown now.  Check the contents of the history
  // table.  We should have only one visit for the URL even though it
  // had 10 parts.
  sql::Connection db;
  FilePath history =
      user_data_dir().AppendASCII("Default").AppendASCII("History");
  ASSERT_TRUE(file_util::PathExists(history));
  ASSERT_TRUE(db.Open(history));
  std::string query(
      "SELECT COUNT(1) FROM visits, urls WHERE visits.url = urls.id"
      " AND urls.url LIKE 'http://localhost:%/multipart'");
  {
    sql::Statement statement(db.GetUniqueStatement(query.c_str()));
    EXPECT_TRUE(statement);
    EXPECT_TRUE(statement.Step());
    EXPECT_EQ(1, statement.ColumnInt(0));
  }
  db.Close();
}
#endif

}  // namespace
<|endoftext|>


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

#include "chrome/browser/net/metadata_url_request.h"

#include "base/file_path.h"
#include "base/message_loop.h"
#include "build/build_config.h"
#include "chrome/browser/parsers/metadata_parser_manager.h"
#include "chrome/browser/parsers/metadata_parser.h"
#include "chrome/common/url_constants.h"
#include "net/base/io_buffer.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"

namespace {

const char kMetadataScheme[] = "metadata";

class MetadataRequestHandler : public URLRequestJob {
 public:
  explicit MetadataRequestHandler(URLRequest* request);

  static URLRequestJob* Factory(URLRequest* request, const std::string& scheme);

  // URLRequestJob implementation.
  virtual void Start();
  virtual void Kill();
  virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
  virtual bool GetMimeType(std::string* mime_type) const;

 private:
  ~MetadataRequestHandler();

  void StartAsync();
  std::string result_;
  bool parsed;
  int data_offset_;
  DISALLOW_COPY_AND_ASSIGN(MetadataRequestHandler);
};

MetadataRequestHandler::MetadataRequestHandler(URLRequest* request)
    : URLRequestJob(request),
      data_offset_(0) {
  parsed = false;
}

MetadataRequestHandler::~MetadataRequestHandler() {
}

URLRequestJob* MetadataRequestHandler::Factory(URLRequest* request,
                                               const std::string& scheme) {
  return new MetadataRequestHandler(request);
}

void MetadataRequestHandler::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
      this, &MetadataRequestHandler::StartAsync));
}

void MetadataRequestHandler::Kill() {
}

bool MetadataRequestHandler::ReadRawData(net::IOBuffer* buf, int buf_size,
                                         int *bytes_read) {
  FilePath path;

  if (!request()->url().is_valid()) {
    return false;
  }
  if (!net::FileURLToFilePath(request()->url(), &path)) {
    return false;
  }
  if (!parsed) {
    MetadataParserManager* manager = MetadataParserManager::Get();
    scoped_ptr<MetadataParser> parser(manager->GetParserForFile(path));
    if (parser != NULL) {
      result_ = "{\n";
      parser->Parse();
      MetadataPropertyIterator *iter = parser->GetPropertyIterator();
      while (!iter->IsEnd()) {
        std::string key;
        std::string value;
        if (iter->GetNext(&key, &value)) {
          result_ += "\"";
          result_ += key;
          result_ += "\":";
          result_ += "\"";
          result_ += value;
          result_ += "\",\n";
        } else {
          break;
        }
      }
      result_ += "}";
      delete iter;
    } else {
      result_ = "{}";
    }
    parsed = true;
  }
  int remaining = static_cast<int>(result_.size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), &result_[data_offset_], buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
  return true;
}

bool MetadataRequestHandler::GetMimeType(std::string* mime_type) const {
  *mime_type = "application/json";
  return true;
}

void MetadataRequestHandler::StartAsync() {
  NotifyHeadersComplete();
}

}  // namespace

void RegisterMetadataURLRequestHandler() {
#if defined(OS_CHROMEOS)
  URLRequest::RegisterProtocolFactory(chrome::kMetadataScheme,
                                      &MetadataRequestHandler::Factory);
#endif
}
<commit_msg>Try to fix CrOS build.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/metadata_url_request.h"

#include "base/file_path.h"
#include "base/message_loop.h"
#include "build/build_config.h"
#include "chrome/browser/parsers/metadata_parser_manager.h"
#include "chrome/browser/parsers/metadata_parser.h"
#include "chrome/common/url_constants.h"
#include "net/base/io_buffer.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"

namespace {

class MetadataRequestHandler : public URLRequestJob {
 public:
  explicit MetadataRequestHandler(URLRequest* request);

  static URLRequestJob* Factory(URLRequest* request, const std::string& scheme);

  // URLRequestJob implementation.
  virtual void Start();
  virtual void Kill();
  virtual bool ReadRawData(net::IOBuffer* buf, int buf_size, int *bytes_read);
  virtual bool GetMimeType(std::string* mime_type) const;

 private:
  ~MetadataRequestHandler();

  void StartAsync();
  std::string result_;
  bool parsed;
  int data_offset_;
  DISALLOW_COPY_AND_ASSIGN(MetadataRequestHandler);
};

MetadataRequestHandler::MetadataRequestHandler(URLRequest* request)
    : URLRequestJob(request),
      data_offset_(0) {
  parsed = false;
}

MetadataRequestHandler::~MetadataRequestHandler() {
}

URLRequestJob* MetadataRequestHandler::Factory(URLRequest* request,
                                               const std::string& scheme) {
  return new MetadataRequestHandler(request);
}

void MetadataRequestHandler::Start() {
  // Start reading asynchronously so that all error reporting and data
  // callbacks happen as they would for network requests.
  MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
      this, &MetadataRequestHandler::StartAsync));
}

void MetadataRequestHandler::Kill() {
}

bool MetadataRequestHandler::ReadRawData(net::IOBuffer* buf, int buf_size,
                                         int *bytes_read) {
  FilePath path;

  if (!request()->url().is_valid()) {
    return false;
  }
  if (!net::FileURLToFilePath(request()->url(), &path)) {
    return false;
  }
  if (!parsed) {
    MetadataParserManager* manager = MetadataParserManager::Get();
    scoped_ptr<MetadataParser> parser(manager->GetParserForFile(path));
    if (parser != NULL) {
      result_ = "{\n";
      parser->Parse();
      MetadataPropertyIterator *iter = parser->GetPropertyIterator();
      while (!iter->IsEnd()) {
        std::string key;
        std::string value;
        if (iter->GetNext(&key, &value)) {
          result_ += "\"";
          result_ += key;
          result_ += "\":";
          result_ += "\"";
          result_ += value;
          result_ += "\",\n";
        } else {
          break;
        }
      }
      result_ += "}";
      delete iter;
    } else {
      result_ = "{}";
    }
    parsed = true;
  }
  int remaining = static_cast<int>(result_.size()) - data_offset_;
  if (buf_size > remaining)
    buf_size = remaining;
  if (buf_size > 0) {
    memcpy(buf->data(), &result_[data_offset_], buf_size);
    data_offset_ += buf_size;
  }
  *bytes_read = buf_size;
  return true;
}

bool MetadataRequestHandler::GetMimeType(std::string* mime_type) const {
  *mime_type = "application/json";
  return true;
}

void MetadataRequestHandler::StartAsync() {
  NotifyHeadersComplete();
}

}  // namespace

void RegisterMetadataURLRequestHandler() {
#if defined(OS_CHROMEOS)
  URLRequest::RegisterProtocolFactory(chrome::kMetadataScheme,
                                      &MetadataRequestHandler::Factory);
#endif
}
<|endoftext|>


<commit_before><commit_msg>- more work on new code generator<commit_after><|endoftext|>


<commit_before>#include "./test_group.hpp"
#include <string>

namespace c4 {
namespace yml {

/**
    See also issue 263.
 */

C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wuseless-cast")

constexpr const NodeType_e DQV = (NodeType_e)(DOC | QV);

TEST(empty_scalar, parse_zero_length_strings)
{
    char inp[] = R"(
- ""
- ''
- >
- |
)";

    Tree tr = parse_in_place(inp);

    ASSERT_EQ(tr.rootref().num_children(), 4);
    for(const auto &child : tr.rootref().children())
    {
        ASSERT_EQ(child.type(), QV);
        ASSERT_EQ(child.val(), "");
        ASSERT_FALSE(child.val_is_null());
    }
}

TEST(empty_scalar, build_zero_length_string)
{
    Tree tr;
    NodeRef root = tr.rootref();
    root |= MAP;

    NodeRef non_quoted = root["non_quoted"];
    non_quoted |= SEQ;

    const std::string e;  // empty std::string

    non_quoted.append_child() << "";
    non_quoted.append_child() = "";
    non_quoted.append_child() << e;

    NodeRef quoted = root["quoted"];
    quoted |= SEQ;
    {auto r = quoted.append_child(); r << ""; r.set_type(r.type() | VALQUO);}
    {auto r = quoted.append_child(); r = "";  r.set_type(r.type() | VALQUO);}
    {auto r = quoted.append_child(); r << e;  r.set_type(r.type() | VALQUO);}

    ASSERT_EQ(non_quoted.num_children(), 3);
    for(const auto &child : non_quoted.children())
    {
        EXPECT_EQ(child.type(), VAL);
        EXPECT_EQ(child.val(), "");
        EXPECT_FALSE(child.val_is_null());
    }

    ASSERT_EQ(quoted.num_children(), 3);
    for(const auto &child : quoted.children())
    {
        EXPECT_EQ(child.type(), VAL | VALQUO);
        EXPECT_EQ(child.val(), "");
        EXPECT_FALSE(child.val_is_null());
    }
}

CASE_GROUP(EMPTY_SCALAR)
{
ADD_CASE_TO_GROUP("empty scalar, single quoted",
                  "''",
                  N(DQV, "")
);
}

} // namespace yml
} // namespace c4

C4_SUPPRESS_WARNING_GCC_POP
<commit_msg>[impl] refine required behavior with null/non-null empty scalars<commit_after>#include "./test_group.hpp"
#include <string>

namespace c4 {
namespace yml {

// See also issue 263: https://github.com/biojppm/rapidyaml/issues/263

C4_SUPPRESS_WARNING_GCC_WITH_PUSH("-Wuseless-cast")

constexpr const NodeType_e DQV = (NodeType_e)(DOC | QV);

TEST(empty_scalar, parse_zero_length_strings)
{
    char inp[] = R"(
seq:
  - ""
  - ''
  - >
  - |
map:
  a: ""
  b: ''
  c: >
  d: |
)";
    const Tree tr = parse_in_place(inp);
    EXPECT_TRUE(tr["seq"].has_key());
    EXPECT_TRUE(tr["map"].has_key());
    EXPECT_TRUE(tr["seq"].is_seq());
    EXPECT_TRUE(tr["map"].is_map());
    for(const char *name : {"seq", "map"})
    {
        NodeRef node = tr[to_csubstr(name)];
        ASSERT_EQ(node.num_children(), 4);
        for(const auto &child : node.children())
        {
            EXPECT_TRUE(child.is_val_quoted());
            EXPECT_EQ(child.val(), "");
            EXPECT_FALSE(child.val_is_null());
        }
    }
}

TEST(empty_scalar, parse_empty_strings)
{
    char inp[] = R"(
# use multiple empty entries to ensure the parser
# correctly deals with the several cases
seq:
  -
  -
  -
  -
map:
  a:
  b:
  c:
  d:
)";
    const Tree tr = parse_in_place(inp);
    for(const char *name : {"seq", "map"})
    {
        NodeRef node = tr[to_csubstr(name)];
        ASSERT_EQ(node.num_children(), 4);
        for(const auto &child : node.children())
        {
            EXPECT_FALSE(child.type().is_val_quoted());
            EXPECT_EQ(child.val(), "");
            EXPECT_TRUE(child.val_is_null());
        }
    }
}

TEST(empty_scalar, build_zero_length_string)
{
    Tree tr;
    NodeRef root = tr.rootref();
    root |= MAP;
    auto addseq = [&root](csubstr name) { NodeRef n = root[name]; n |= SEQ; return n; };

    // try both with nonnull-zero-length and null-zero-length
    csubstr empty = csubstr("nonempty").first(0);
    csubstr nullss = {};

    // these are the conditions we wish to cover:
    ASSERT_TRUE(nullss.str == nullptr);
    ASSERT_TRUE(nullss.len == 0u);
    ASSERT_TRUE(empty.str != nullptr);
    ASSERT_TRUE(empty.len == 0u);

    // = and << must have exactly the same behavior where nullity is
    // regarded

    // quoted cases will never be null, regardless of the
    // incoming scalar
    NodeRef quoted = addseq("quoted");
    {NodeRef r = quoted.append_child(); r = ""      ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r << ""     ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r = empty   ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r << empty  ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r = nullss  ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r << nullss ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r = nullptr ; r.set_type(r.type() | VALQUO);}
    {NodeRef r = quoted.append_child(); r << nullptr; r.set_type(r.type() | VALQUO);}
    ASSERT_TRUE(quoted.has_children());
    for(const auto &child : quoted.children())
    {
        EXPECT_TRUE(child.is_val_quoted());
        EXPECT_EQ(child.val(), "");
        EXPECT_EQ(child.val(), nullptr);
        EXPECT_FALSE(child.val_is_null());
    }

    // ... but according to the incoming scalar, non quoted cases may
    // or may not be null
    NodeRef non_quoted = addseq("nonquoted");
    non_quoted.append_child() = "";
    non_quoted.append_child() << "";
    non_quoted.append_child() = empty;
    non_quoted.append_child() << empty;
    non_quoted.append_child() = nullss;
    non_quoted.append_child() << nullss;
    non_quoted.append_child() = nullptr;
    non_quoted.append_child() << nullptr;
    ASSERT_TRUE(non_quoted.has_children());
    size_t pos = 0;
    for(const auto &child : non_quoted.children())
    {
        EXPECT_TRUE(child.is_val());
        EXPECT_EQ(child.val(), "");
        EXPECT_EQ(child.val(), nullptr);
        if(pos < 4u)
            EXPECT_FALSE(child.val_is_null()) << "pos=" << pos;
        else
            EXPECT_TRUE(child.val_is_null()) << "pos=" << pos;
        ++pos;
    }
}

CASE_GROUP(EMPTY_SCALAR)
{
ADD_CASE_TO_GROUP("empty scalar, single quoted",
                  "''",
                  N(DQV, "")
);
}

} // namespace yml
} // namespace c4

C4_SUPPRESS_WARNING_GCC_POP
<|endoftext|>


<commit_before>#include <boost/format.hpp>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <fstream>
#include <cmath>

namespace cap {

void compute_energy(std::vector<std::string> const & capacitor_state,
    std::vector<double> const & time,
    std::vector<double> const & power,
    std::vector<double> & energy)

{
    bool const valid_input =
           (time.size() == power.size())
        && (time.size() == energy.size())
        && (time.size() == capacitor_state.size())
        ;
    if (!valid_input) throw std::runtime_error("invalid input");
    std::vector<std::string>::const_iterator it     = capacitor_state.begin();
    std::vector<std::string>::const_iterator end_it = capacitor_state.end();
    std::size_t first =  0;
    while (it != end_it)
    {
        auto same = [&it] (std::string const & o) { return it->compare(o) == 0; };
        std::vector<std::string>::const_iterator next = std::find_if_not(it, end_it, same);
        std::size_t last = first + std::distance(it, next);
        energy[first] = 0.0;
        for (std::size_t pos = first + 1; pos < last; ++pos)
            energy[pos] = energy[pos-1] + 0.5 * (time[pos] - time[pos-1]) * (power[pos] + power[pos-1]);
        it = next;
        first = last;
    }
}

void extract_duration_and_average_power(std::vector<std::string> const & capacitor_state,
    std::vector<double> const & time,
    std::vector<double> const & energy,
    std::vector<double> & duration,
    std::vector<double> & average_power)
{
    bool const valid_input = (time.size() == energy.size())
        && duration.empty()
        && average_power.empty()
        ;
    if (!valid_input) throw std::runtime_error("invalid input");
    std::vector<std::string>::const_iterator it     = capacitor_state.begin();
    std::vector<std::string>::const_iterator end_it = capacitor_state.end();
    std::size_t first =  0;
    while (it != end_it)
    {
        auto same = [&it] (std::string const & o) { return it->compare(o) == 0; };
        std::vector<std::string>::const_iterator next = std::find_if_not(it, end_it, same);
        std::size_t last = first + std::distance(it, next);
        duration.push_back(time[last-1] - time[first]);
        average_power.push_back((energy[last-1] - energy[first]) / duration.back());
        it = next;
        first = last;
    }
}

} // end namespace cap

//  #!/usr/bin/env python
//  from pylab import *
//  data=loadtxt("data",usecols=(0,2,3))
//  time=data[:,0]
//  power=data[:,1]
//  energy=data[:,2]
//  fig,axarr=subplots(2,sharex=True)
//  axarr[0].plot(time,power)
//  axarr[0].set_ylabel("power")
//  axarr[1].plot(time,energy)
//  axarr[1].set_xlabel("time")
//  axarr[1].set_ylabel("energy")
//  show()

int main(int argc, char *argv[])
{
    std::fstream fout("data", std::fstream::out);
    std::ostream & os = fout;
    bool const verbose = true;

    double const initial_time = 0.0;
    double const final_time   = 2.0;
    std::size_t const n = 10001;
    double const pi = 3.14159265359;
    std::vector<double> time(n);
    std::vector<double> power(n);
    std::vector<std::string> capacitor_state(n);

    // INITIALIZE SOLUTION
    for (std::size_t i = 0; i < n; ++i) {
        time[i] = initial_time + static_cast<double>(i) / (n - 1) * (final_time - initial_time);
        power[i] = std::cos(2.0 * pi * time[i]);
        capacitor_state[i] = (power[i] > 0.0 ? "charging" : "discharging");
    }

    // COMPUTE ENERGY
    std::vector<double> energy(n);
    cap::compute_energy(capacitor_state, time, power, energy);

    // GET DURATION AND AVERAGED POWER
    std::vector<double> duration;
    std::vector<double> average_power;
    cap::extract_duration_and_average_power(capacitor_state, time, energy, duration, average_power);

    for (std::size_t i = 0; i < duration.size(); ++i)
        std::cout<<duration[i]<<"  "<<average_power[i]<<"\n";

    // CHECK THE ANSWER
    std::vector<double> exact(n);
    std::vector<double> error(n);
    double correction = 0.0;
    exact[0] = 0.0;
    for (std::size_t i = 0; i < n; ++i) {
        exact[i] = 0.5 / pi * std::sin(2.0 * pi * time[i]) - correction;
        error[i] = energy[i] - exact[i];
    }

    // PRINT TO THE STREAM
    if (verbose)
        for (std::size_t i = 0; i < n; ++i)
            os<<boost::format("  %10.5f  %15s  %10.5f  %10.5f  %10.5f  %10.5f \n")
                % time[i]
                % capacitor_state[i]
                % power[i]
                % energy[i]
                % exact[i]
                % error[i]
                ;

    return 0;
}
<commit_msg>template for compute integral with trapezoid<commit_after>#include <boost/format.hpp>
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <fstream>
#include <cmath>

namespace cap {

template <class InputIterator1, class InputIterator2,
          class OutputIterator, class T>
void approximate_integral_with_trapezoidal_rule
    (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2,
     OutputIterator result, T init)
{
    *result = init;
    ++first1; ++first2; ++result;
    while (first1 != last1)
    {
        *result = *std::prev(result) + 0.5 * (*first1 - *std::prev(first1)) * (*first2 + *std::prev(first2));
        ++first1; ++first2; ++result;
    }

}

void compute_energy(std::vector<std::string> const & capacitor_state,
    std::vector<double> const & time,
    std::vector<double> const & power,
    std::vector<double> & energy)

{
    bool const valid_input =
           (time.size() == power.size())
        && (time.size() == energy.size())
        && (time.size() == capacitor_state.size())
        ;
    if (!valid_input) throw std::runtime_error("invalid input");
    std::vector<std::string>::const_iterator it     = capacitor_state.begin();
    std::vector<std::string>::const_iterator end_it = capacitor_state.end();
    std::size_t first =  0;
    while (it != end_it)
    {
        auto same = [&it] (std::string const & o) { return it->compare(o) == 0; };
        std::vector<std::string>::const_iterator next = std::find_if_not(it, end_it, same);
        std::size_t last = first + std::distance(it, next);
        approximate_integral_with_trapezoidal_rule(std::next(time.begin(), first), std::next(time.begin(), last),
                                                   std::next(power.begin(), first),
                                                   std::next(energy.begin(), first), 0.0);
        it = next;
        first = last;
    }
}

void extract_duration_and_average_power(std::vector<std::string> const & capacitor_state,
    std::vector<double> const & time,
    std::vector<double> const & energy,
    std::vector<double> & duration,
    std::vector<double> & average_power)
{
    bool const valid_input = (time.size() == energy.size())
        && duration.empty()
        && average_power.empty()
        ;
    if (!valid_input) throw std::runtime_error("invalid input");
    std::vector<std::string>::const_iterator it     = capacitor_state.begin();
    std::vector<std::string>::const_iterator end_it = capacitor_state.end();
    std::size_t first =  0;
    while (it != end_it)
    {
        auto same = [&it] (std::string const & o) { return it->compare(o) == 0; };
        std::vector<std::string>::const_iterator next = std::find_if_not(it, end_it, same);
        std::size_t last = first + std::distance(it, next);
        duration.push_back(time[last-1] - time[first]);
        average_power.push_back((energy[last-1] - energy[first]) / duration.back());
        it = next;
        first = last;
    }
}

} // end namespace cap

//  #!/usr/bin/env python
//  from pylab import *
//  data=loadtxt("data",usecols=(0,2,3))
//  time=data[:,0]
//  power=data[:,1]
//  energy=data[:,2]
//  fig,axarr=subplots(2,sharex=True)
//  axarr[0].plot(time,power)
//  axarr[0].set_ylabel("power")
//  axarr[1].plot(time,energy)
//  axarr[1].set_xlabel("time")
//  axarr[1].set_ylabel("energy")
//  show()

int main(int argc, char *argv[])
{
    std::fstream fout("data", std::fstream::out);
    std::ostream & os = fout;
    bool const verbose = true;

    double const initial_time = 0.0;
    double const final_time   = 2.0;
    std::size_t const n = 10001;
    double const pi = 3.14159265359;
    std::vector<double> time(n);
    std::vector<double> power(n);
    std::vector<std::string> capacitor_state(n);

    // INITIALIZE SOLUTION
    for (std::size_t i = 0; i < n; ++i) {
        time[i] = initial_time + static_cast<double>(i) / (n - 1) * (final_time - initial_time);
        power[i] = std::cos(2.0 * pi * time[i]);
        capacitor_state[i] = (power[i] > 0.0 ? "charging" : "discharging");
    }

    // COMPUTE ENERGY
    std::vector<double> energy(n);
    cap::compute_energy(capacitor_state, time, power, energy);

    // GET DURATION AND AVERAGED POWER
    std::vector<double> duration;
    std::vector<double> average_power;
    cap::extract_duration_and_average_power(capacitor_state, time, energy, duration, average_power);

    for (std::size_t i = 0; i < duration.size(); ++i)
        std::cout<<duration[i]<<"  "<<average_power[i]<<"\n";

    // CHECK THE ANSWER
    std::vector<double> exact(n);
    std::vector<double> error(n);
    double correction = 0.0;
    exact[0] = 0.0;
    for (std::size_t i = 0; i < n; ++i) {
        exact[i] = 0.5 / pi * std::sin(2.0 * pi * time[i]) - correction;
        error[i] = energy[i] - exact[i];
    }

    // PRINT TO THE STREAM
    if (verbose)
        for (std::size_t i = 0; i < n; ++i)
            os<<boost::format("  %10.5f  %15s  %10.5f  %10.5f  %10.5f  %10.5f \n")
                % time[i]
                % capacitor_state[i]
                % power[i]
                % energy[i]
                % exact[i]
                % error[i]
                ;

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "gtest/gtest.h"

#include "sigs.h"

TEST(General, instantiate)
{
  sigs::Signal<void()> s;
  sigs::Signal<void(int)> s2;
  sigs::Signal<int()> s3;
}

inline void addOne(int &i)
{
  i++;
}

TEST(General, function)
{
  sigs::Signal<void(int &)> s;
  s.connect(addOne);

  int i = 0;
  s(i);

  EXPECT_EQ(i, 1);
}

TEST(General, multipleFunctions)
{
  sigs::Signal<void(int &)> s;
  s.connect(addOne);
  s.connect(addOne);
  s.connect(addOne);

  int i = 0;
  s(i);

  EXPECT_EQ(i, 3);
}

TEST(General, functor)
{
  class AddOneFunctor {
  public:
    void operator()(int &i)
    {
      i++;
    }
  };

  sigs::Signal<void(int &)> s;
  s.connect(AddOneFunctor());

  int i = 0;
  s(i);

  EXPECT_EQ(i, 1);
}

TEST(General, instanceMethod)
{
  class Foo {
  public:
    void test(int &i)
    {
      i++;
    }
  };

  sigs::Signal<void(int &)> s;

  Foo foo;
  s.connect(&foo, &Foo::test);

  int i = 0;
  s(i);

  EXPECT_EQ(i, 1);
}

TEST(General, lambda)
{
  sigs::Signal<void(int &)> s;
  s.connect([](int &i) { i++; });

  int i = 0;
  s(i);
  EXPECT_EQ(i, 1);
}

TEST(General, connectionDisconnectDirectly)
{
  sigs::Signal<void(int &)> s;
  auto conn = s.connect([](int &i) { i++; });

  int i = 0;
  s(i);
  EXPECT_EQ(i, 1);

  conn->disconnect();

  s(i);
  EXPECT_EQ(i, 1);
}

TEST(General, connectionDisconnectOnSignal)
{
  sigs::Signal<void(int &)> s;
  auto conn = s.connect([](int &i) { i++; });

  int i = 0;
  s(i);
  EXPECT_EQ(i, 1);

  s.disconnect(conn);

  s(i);
  EXPECT_EQ(i, 1);
}

TEST(General, connectSignalToSignal)
{
  sigs::Signal<void(int &)> s1;
  s1.connect([](int &i) { i++; });

  decltype(s1) s2;
  s2.connect(s1);

  int i = 0;
  s2(i);
  EXPECT_EQ(i, 1);
}

TEST(General, disconnectSignalFromSignal)
{
  sigs::Signal<void(int &)> s1;
  s1.connect([](int &i) { i++; });

  decltype(s1) s2;
  s2.connect(s1);
  s2.disconnect(s1);

  int i = 0;
  s2(i);
  EXPECT_EQ(i, 0);
}

TEST(General, ambiguousMembers)
{
  class Ambiguous {
  public:
    void foo(int i)
    {
      value += i;
    }

    void foo(float j)
    {
      value += static_cast<int>(j);
    }

    int value = 0;
  };

  sigs::Signal<void(int)> s;

  Ambiguous amb;
  auto conn = s.connect(&amb, sigs::Use<int>::overloadOf(&Ambiguous::foo));
  s(42);
  EXPECT_EQ(amb.value, 42);
  conn->disconnect();

  // This one only works because int can be coerced into float.
  s.connect(&amb, sigs::Use<float>::overloadOf(&Ambiguous::foo));
  s(1);
  EXPECT_EQ(amb.value, 43);
}

TEST(General, returnValues)
{
  sigs::Signal<int()> s;
  s.connect([] { return 1; });
  s.connect([] { return 2; });
  s.connect([] { return 3; });

  int sum = 0;
  s([&sum](int retVal) { sum += retVal; });

  EXPECT_EQ(sum, 1 + 2 + 3);
}

TEST(General, sameSlotManyConnections)
{
  int calls = 0;
  const auto slot = [&calls] { calls++; };

  sigs::Signal<void()> s;
  s.connect(slot);
  s();
  EXPECT_EQ(calls, 1);

  s.connect(slot);
  s();
  EXPECT_EQ(calls, 3);

  // This yielded 4 calls when eraseEntries() didn't clear correctly.
  s.clear();
  s();
  EXPECT_EQ(calls, 3);
}
<commit_msg>Test clear is equivalent to all disconnects<commit_after>#include <iostream>

#include "gtest/gtest.h"

#include "sigs.h"

TEST(General, instantiate)
{
  sigs::Signal<void()> s;
  sigs::Signal<void(int)> s2;
  sigs::Signal<int()> s3;
}

inline void addOne(int &i)
{
  i++;
}

TEST(General, function)
{
  sigs::Signal<void(int &)> s;
  s.connect(addOne);

  int i = 0;
  s(i);

  EXPECT_EQ(i, 1);
}

TEST(General, multipleFunctions)
{
  sigs::Signal<void(int &)> s;
  s.connect(addOne);
  s.connect(addOne);
  s.connect(addOne);

  int i = 0;
  s(i);

  EXPECT_EQ(i, 3);
}

TEST(General, functor)
{
  class AddOneFunctor {
  public:
    void operator()(int &i)
    {
      i++;
    }
  };

  sigs::Signal<void(int &)> s;
  s.connect(AddOneFunctor());

  int i = 0;
  s(i);

  EXPECT_EQ(i, 1);
}

TEST(General, instanceMethod)
{
  class Foo {
  public:
    void test(int &i)
    {
      i++;
    }
  };

  sigs::Signal<void(int &)> s;

  Foo foo;
  s.connect(&foo, &Foo::test);

  int i = 0;
  s(i);

  EXPECT_EQ(i, 1);
}

TEST(General, lambda)
{
  sigs::Signal<void(int &)> s;
  s.connect([](int &i) { i++; });

  int i = 0;
  s(i);
  EXPECT_EQ(i, 1);
}

TEST(General, connectionDisconnectDirectly)
{
  sigs::Signal<void(int &)> s;
  auto conn = s.connect([](int &i) { i++; });

  int i = 0;
  s(i);
  EXPECT_EQ(i, 1);

  conn->disconnect();

  s(i);
  EXPECT_EQ(i, 1);
}

TEST(General, connectionDisconnectOnSignal)
{
  sigs::Signal<void(int &)> s;
  auto conn = s.connect([](int &i) { i++; });

  int i = 0;
  s(i);
  EXPECT_EQ(i, 1);

  s.disconnect(conn);

  s(i);
  EXPECT_EQ(i, 1);
}

TEST(General, connectSignalToSignal)
{
  sigs::Signal<void(int &)> s1;
  s1.connect([](int &i) { i++; });

  decltype(s1) s2;
  s2.connect(s1);

  int i = 0;
  s2(i);
  EXPECT_EQ(i, 1);
}

TEST(General, disconnectSignalFromSignal)
{
  sigs::Signal<void(int &)> s1;
  s1.connect([](int &i) { i++; });

  decltype(s1) s2;
  s2.connect(s1);
  s2.disconnect(s1);

  int i = 0;
  s2(i);
  EXPECT_EQ(i, 0);
}

TEST(General, ambiguousMembers)
{
  class Ambiguous {
  public:
    void foo(int i)
    {
      value += i;
    }

    void foo(float j)
    {
      value += static_cast<int>(j);
    }

    int value = 0;
  };

  sigs::Signal<void(int)> s;

  Ambiguous amb;
  auto conn = s.connect(&amb, sigs::Use<int>::overloadOf(&Ambiguous::foo));
  s(42);
  EXPECT_EQ(amb.value, 42);
  conn->disconnect();

  // This one only works because int can be coerced into float.
  s.connect(&amb, sigs::Use<float>::overloadOf(&Ambiguous::foo));
  s(1);
  EXPECT_EQ(amb.value, 43);
}

TEST(General, returnValues)
{
  sigs::Signal<int()> s;
  s.connect([] { return 1; });
  s.connect([] { return 2; });
  s.connect([] { return 3; });

  int sum = 0;
  s([&sum](int retVal) { sum += retVal; });

  EXPECT_EQ(sum, 1 + 2 + 3);
}

TEST(General, sameSlotManyConnections)
{
  int calls = 0;
  const auto slot = [&calls] { calls++; };

  sigs::Signal<void()> s;
  s.connect(slot);
  s();
  EXPECT_EQ(calls, 1);

  s.connect(slot);
  s();
  EXPECT_EQ(calls, 3);

  // This yielded 4 calls when eraseEntries() didn't clear correctly.
  s.clear();
  s();
  EXPECT_EQ(calls, 3);
}

TEST(General, clearEquivalentToAllDisconnects)
{
  int calls = 0;
  const auto slot = [&calls] { calls++; };

  sigs::Signal<void()> s;

  {
    calls = 0;
    auto conn1 = s.connect(slot);
    auto conn2 = s.connect(slot);
    s();
    EXPECT_EQ(calls, 2);

    s.clear();
    s();
    EXPECT_EQ(calls, 2);
  }

  {
    calls = 0;
    auto conn1 = s.connect(slot);
    auto conn2 = s.connect(slot);
    s();
    EXPECT_EQ(calls, 2);

    s.disconnect(conn1);
    s.disconnect(conn2);
    s();
    EXPECT_EQ(calls, 2);
  }
}
<|endoftext|>


<commit_before>/*
 *  decode.cpp - h264 decode test
 *
 *  Copyright (C) 2011-2014 Intel Corporation
 *    Author: Halley Zhao<halley.zhao@intel.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This 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
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

#include "common/log.h"
#include "common/utils.h"
#include "VideoDecoderHost.h"
#include "decodeinput.h"
#include "decodeoutput.h"
#include "decodehelp.h"
#ifdef __ENABLE_X11__
#include <X11/Xlib.h>
#endif

using namespace YamiMediaCodec;

int main(int argc, char** argv)
{
    IVideoDecoder *decoder = NULL;
    DecodeInput *input;
    DecodeOutput *output;
    VideoDecodeBuffer inputBuffer;
    VideoConfigBuffer configBuffer;
    const VideoFormatInfo *formatInfo = NULL;
    Decode_Status status;
    class CalcFps calcFpsGross, calcFpsNet;
    int skipFrameCount4NetFps = 0;
#ifdef __ENABLE_X11__
    XInitThreads();
#endif
    calcFpsGross.setAnchor();
    yamiTraceInit();
    if (!process_cmdline(argc, argv))
        return -1;
#if !__ENABLE_TESTS_GLES__
    if (renderMode > 1) {
        fprintf(stderr, "renderMode=%d is not supported, please rebuild with --enable-tests-gles option\n", renderMode);
        return -1;
    }
#endif
    input = DecodeInput::create(inputFileName);

    if (input==NULL) {
        fprintf(stderr, "fail to init input stream\n");
        return -1;
    }

    decoder = createVideoDecoder(input->getMimeType());
    assert(decoder != NULL);

    output = DecodeOutput::create(decoder, renderMode);
    if (!output || !configDecodeOutput(output)) {
        fprintf(stderr, "failed to config decode output of mode: %d\n", renderMode);
        return -1;
    }

    memset(&configBuffer,0,sizeof(VideoConfigBuffer));
    configBuffer.profile = VAProfileNone;

    status = decoder->start(&configBuffer);
    assert(status == DECODE_SUCCESS);

    while (!input->isEOS())
    {
        if (input->getNextDecodeUnit(inputBuffer)){
            status = decoder->decode(&inputBuffer);
        } else
            break;

        if (DECODE_FORMAT_CHANGE == status) {
            formatInfo = decoder->getFormatInfo();
            if (!output->setVideoSize(formatInfo->width, formatInfo->height)) {
                assert(0 && "set video size failed");
                break;
            }
            // resend the buffer
            status = decoder->decode(&inputBuffer);
        }

        renderOutputFrames(output);
        if (output->renderFrameCount() >= 5 && !skipFrameCount4NetFps) {
            skipFrameCount4NetFps = output->renderFrameCount();
            calcFpsNet.setAnchor();
        }
    }

#if 0
    // send EOS to decoder
    inputBuffer.data = NULL;
    inputBuffer.size = 0;
    status = decoder->decode(&inputBuffer);
#endif

    // drain the output buffer
    renderOutputFrames(output, true);

    calcFpsGross.fps(output->renderFrameCount());
    if (output->renderFrameCount() > skipFrameCount4NetFps)
        calcFpsNet.fps(output->renderFrameCount()-skipFrameCount4NetFps);

    possibleWait(input->getMimeType());

    decoder->stop();
    releaseVideoDecoder(decoder);

    delete input;
    delete output;

    if (dumpOutputDir)
        free(dumpOutputDir);
    fprintf(stderr, "decode done\n");
}
<commit_msg>tests: revert XInitThreads() in yamidecode -- need more investigation<commit_after>/*
 *  decode.cpp - h264 decode test
 *
 *  Copyright (C) 2011-2014 Intel Corporation
 *    Author: Halley Zhao<halley.zhao@intel.com>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This 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
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

#include "common/log.h"
#include "common/utils.h"
#include "VideoDecoderHost.h"
#include "decodeinput.h"
#include "decodeoutput.h"
#include "decodehelp.h"
#ifdef __ENABLE_X11__
// #include <X11/Xlib.h>
#endif

using namespace YamiMediaCodec;

int main(int argc, char** argv)
{
    IVideoDecoder *decoder = NULL;
    DecodeInput *input;
    DecodeOutput *output;
    VideoDecodeBuffer inputBuffer;
    VideoConfigBuffer configBuffer;
    const VideoFormatInfo *formatInfo = NULL;
    Decode_Status status;
    class CalcFps calcFpsGross, calcFpsNet;
    int skipFrameCount4NetFps = 0;
#ifdef __ENABLE_X11__
    // XInitThreads();
#endif
    calcFpsGross.setAnchor();
    yamiTraceInit();
    if (!process_cmdline(argc, argv))
        return -1;
#if !__ENABLE_TESTS_GLES__
    if (renderMode > 1) {
        fprintf(stderr, "renderMode=%d is not supported, please rebuild with --enable-tests-gles option\n", renderMode);
        return -1;
    }
#endif
    input = DecodeInput::create(inputFileName);

    if (input==NULL) {
        fprintf(stderr, "fail to init input stream\n");
        return -1;
    }

    decoder = createVideoDecoder(input->getMimeType());
    assert(decoder != NULL);

    output = DecodeOutput::create(decoder, renderMode);
    if (!output || !configDecodeOutput(output)) {
        fprintf(stderr, "failed to config decode output of mode: %d\n", renderMode);
        return -1;
    }

    memset(&configBuffer,0,sizeof(VideoConfigBuffer));
    configBuffer.profile = VAProfileNone;

    status = decoder->start(&configBuffer);
    assert(status == DECODE_SUCCESS);

    while (!input->isEOS())
    {
        if (input->getNextDecodeUnit(inputBuffer)){
            status = decoder->decode(&inputBuffer);
        } else
            break;

        if (DECODE_FORMAT_CHANGE == status) {
            formatInfo = decoder->getFormatInfo();
            if (!output->setVideoSize(formatInfo->width, formatInfo->height)) {
                assert(0 && "set video size failed");
                break;
            }
            // resend the buffer
            status = decoder->decode(&inputBuffer);
        }

        renderOutputFrames(output);
        if (output->renderFrameCount() >= 5 && !skipFrameCount4NetFps) {
            skipFrameCount4NetFps = output->renderFrameCount();
            calcFpsNet.setAnchor();
        }
    }

#if 0
    // send EOS to decoder
    inputBuffer.data = NULL;
    inputBuffer.size = 0;
    status = decoder->decode(&inputBuffer);
#endif

    // drain the output buffer
    renderOutputFrames(output, true);

    calcFpsGross.fps(output->renderFrameCount());
    if (output->renderFrameCount() > skipFrameCount4NetFps)
        calcFpsNet.fps(output->renderFrameCount()-skipFrameCount4NetFps);

    possibleWait(input->getMimeType());

    decoder->stop();
    releaseVideoDecoder(decoder);

    delete input;
    delete output;

    if (dumpOutputDir)
        free(dumpOutputDir);
    fprintf(stderr, "decode done\n");
}
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE ExpressionTypeDeduction
#include <boost/test/unit_test.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/element_index.hpp>
#include <vexcl/mba.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/tagged_terminal.hpp>
#include <vexcl/temporary.hpp>
#include <vexcl/vector_view.hpp>
#include "context_setup.hpp"

template <typename T = double>
inline std::array<T, 2> make_array(T x,  T y) {
    std::array<T, 2> p = {{x, y}};
    return p;
}

template <class Result, class Expr>
void check(const Expr &expr) {
    typedef typename vex::detail::return_type<Expr>::type Deduced;

    boost::proto::display_expr( boost::proto::as_child(expr) );
    std::cout << vex::type_name<Deduced>() << std::endl << std::endl;

    BOOST_CHECK( (std::is_same<Deduced, Result>::value) );
}

BOOST_AUTO_TEST_CASE(terminals)
{
    const ssize_t n = 1024;

    vex::vector<double> x;
    vex::vector<int> y;

    check<int>   (5);
    check<double>(4.2);
    check<double>(x);
    check<int>   (y);
    check<size_t>(vex::element_index());

    {
        vex::mba<2, float> *surf= 0;
        check<float>( (*surf)(x, y) );
    }

    {
        vex::SpMatCCSR<double> *A = 0;
        check<double>( (*A) * x );
    }

    {
        std::vector<cl::CommandQueue> q1(1, ctx.queue(0));
        vex::vector<double> x1(q1, n);
        vex::SpMat<double> *A = 0;
        check<double>( vex::make_inline( (*A) * x1 ) );
    }

    check<double>( vex::tag<1>(x) );

    {
        auto tmp = vex::make_temp<1>(x * y);
        check<double>( tmp );
    }

    {
        std::vector<cl::CommandQueue> q1(1, ctx.queue(0));
        vex::vector<int> x1(q1, n);
        vex::slicer<1> slice(vex::extents[n]);
        check<int>( slice[vex::range(0, 2, n)](x1) );
    }
}

BOOST_AUTO_TEST_CASE(logical_expr)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<bool>(x < y);
    check<bool>(5 > pow(x, 2.0 * y));
    check<bool>(!x);
}

BOOST_AUTO_TEST_CASE(nary_expr)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<double>(x + y);
    check<double>(x + 2 * y);
    check<int>   (-y);
}

BOOST_AUTO_TEST_CASE(user_functions)
{
    vex::vector<double> x;
    vex::vector<int> y;

    VEX_FUNCTION(f1, double(double),      "return 42;");
    VEX_FUNCTION(f2, int(double, double), "return 42;");

    check<double>( f1(x) );
    check<int>   ( f2(x, y) );
    check<int>   ( f2(x + y, x - y) );
}

BOOST_AUTO_TEST_CASE(ternary_operator)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<int>( if_else(x < 0, 1, y) );
}

BOOST_AUTO_TEST_CASE(builtin_functions)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<double>( cos(x) - sin(y) );
    check<double>( pow(x, 2.0 * y) );
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Testing deduction of cl vector types with terminals<commit_after>#define BOOST_TEST_MODULE ExpressionTypeDeduction
#include <boost/test/unit_test.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/element_index.hpp>
#include <vexcl/mba.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/tagged_terminal.hpp>
#include <vexcl/temporary.hpp>
#include <vexcl/vector_view.hpp>
#include "context_setup.hpp"

template <typename T = double>
inline std::array<T, 2> make_array(T x,  T y) {
    std::array<T, 2> p = {{x, y}};
    return p;
}

template <class Result, class Expr>
void check(const Expr &expr) {
    typedef typename vex::detail::return_type<Expr>::type Deduced;

    boost::proto::display_expr( boost::proto::as_child(expr) );
    std::cout << vex::type_name<Deduced>() << std::endl << std::endl;

    BOOST_CHECK( (std::is_same<Deduced, Result>::value) );
}

BOOST_AUTO_TEST_CASE(terminals)
{
    const ssize_t n = 1024;

    vex::vector<double>     x;
    vex::vector<int>        y;
    vex::vector<cl_double2> z;

    check<int>       (5);
    check<double>    (4.2);
    check<double>    (x);
    check<int>       (y);
    check<cl_double2>(z);
    check<size_t>(vex::element_index());

    {
        vex::mba<2, float> *surf= 0;
        check<float>( (*surf)(x, y) );
    }

    {
        vex::SpMatCCSR<double> *A = 0;
        check<double>( (*A) * x );
    }

    {
        std::vector<cl::CommandQueue> q1(1, ctx.queue(0));
        vex::vector<double> x1(q1, n);
        vex::SpMat<double> *A = 0;
        check<double>( vex::make_inline( (*A) * x1 ) );
    }

    check<double>( vex::tag<1>(x) );

    {
        auto tmp = vex::make_temp<1>(x * y);
        check<double>( tmp );
    }

    {
        std::vector<cl::CommandQueue> q1(1, ctx.queue(0));
        vex::vector<int> x1(q1, n);
        vex::slicer<1> slice(vex::extents[n]);
        check<int>( slice[vex::range(0, 2, n)](x1) );
    }
}

BOOST_AUTO_TEST_CASE(logical_expr)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<bool>(x < y);
    check<bool>(5 > pow(x, 2.0 * y));
    check<bool>(!x);
}

BOOST_AUTO_TEST_CASE(nary_expr)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<double>(x + y);
    check<double>(x + 2 * y);
    check<int>   (-y);
}

BOOST_AUTO_TEST_CASE(user_functions)
{
    vex::vector<double> x;
    vex::vector<int> y;

    VEX_FUNCTION(f1, double(double),      "return 42;");
    VEX_FUNCTION(f2, int(double, double), "return 42;");

    check<double>( f1(x) );
    check<int>   ( f2(x, y) );
    check<int>   ( f2(x + y, x - y) );
}

BOOST_AUTO_TEST_CASE(ternary_operator)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<int>( if_else(x < 0, 1, y) );
}

BOOST_AUTO_TEST_CASE(builtin_functions)
{
    vex::vector<double> x;
    vex::vector<int> y;

    check<double>( cos(x) - sin(y) );
    check<double>( pow(x, 2.0 * y) );
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


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

#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif

#include "objsh.hxx"
#include "orgmgr.hxx"

//=========================================================================

class SfxDocumentTemplates;
class Path;

//=========================================================================

#ifndef _SFX_HXX

class SfxOrganizeDlg_Impl;

class SfxOrganizeListBox_Impl: public SvTreeListBox
{
    enum BMPTYPE            { BMPTYPE_FOLDER, BMPTYPE_DOC };

friend class SfxOrganizeDlg_Impl;

    Image                   aOpenedFolderBmp;
    Image                   aClosedFolderBmp;
    Image                   aOpenedDocBmp;
    Image                   aClosedDocBmp;

    Image                   aOpenedFolderBmpHC;
    Image                   aClosedFolderBmpHC;
    Image                   aOpenedDocBmpHC;
    Image                   aClosedDocBmpHC;

    SfxOrganizeMgr*         pMgr;
    SfxOrganizeDlg_Impl*    pDlg;

    static BOOL             bDropMoveOk;

    DECL_LINK( OnAsyncExecuteDrop, ExecuteDropEvent* );

protected:
    virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection & );
    virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );
    virtual BOOL NotifyMoving(SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent, ULONG &);
    virtual BOOL NotifyCopying(SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent, ULONG &);
    virtual void RequestingChilds( SvLBoxEntry* pParent );
    virtual long ExpandingHdl();
    virtual BOOL Select( SvLBoxEntry* pEntry, BOOL bSelect=TRUE );

    // new d&d
    virtual DragDropMode    NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* );
    virtual BOOL            NotifyAcceptDrop( SvLBoxEntry* );
    virtual sal_Int8        AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8        ExecuteDrop( const ExecuteDropEvent& rEvt );

public:
    enum DataEnum   { VIEW_TEMPLATES, VIEW_FILES } eViewType;

    SfxOrganizeListBox_Impl( SfxOrganizeDlg_Impl* pDlg, Window* pParent, WinBits, DataEnum );

    DataEnum    GetViewType() const { return eViewType; }
    void        SetViewType(DataEnum eType) { eViewType = eType; }

    void SetMgr(SfxOrganizeMgr *pM) { pMgr = pM; }
    void Reset();
    inline void SetBitmaps(
                    const Image &rOFolderBmp, const Image &rCFolderBmp, const Image &rODocBmp, const Image &rCDocBmp,
                    const Image &rOFolderBmpHC, const Image &rCFolderBmpHC, const Image &rODocBmpHC, const Image &rCDocBmpHC );
    const Image &GetClosedBmp(USHORT nLevel) const;
    const Image &GetOpenedBmp(USHORT nLevel) const;

    virtual PopupMenu*  CreateContextMenu();

private:
    BOOL IsStandard_Impl( SvLBoxEntry *) const;
    BOOL MoveOrCopyTemplates(SvLBox *pSourceBox,
                            SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent,
                            ULONG &rIdx,
                            BOOL bCopy);
    BOOL MoveOrCopyContents(SvLBox *pSourceBox,
                            SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent,
                            ULONG &rIdx,
                            BOOL bCopy);
    inline USHORT       GetDocLevel() const;
    SfxObjectShellRef   GetObjectShell( const Path& );
    BOOL                IsUniqName_Impl( const String &rText,
                                         SvLBoxEntry* pParent, SvLBoxEntry* pEntry = 0 ) const;
    USHORT              GetLevelCount_Impl( SvLBoxEntry* pParent ) const;

    SvLBoxEntry*        InsertEntryByBmpType( const XubString& rText, BMPTYPE eBmpType,
                            SvLBoxEntry* pParent = NULL, BOOL bChildsOnDemand = FALSE,
                            ULONG nPos = LIST_APPEND, void* pUserData = NULL );
};

#endif // _SFX_HXX

//=========================================================================

class SfxTemplateOrganizeDlg : public ModalDialog
{
friend class SfxOrganizeListBox_Impl;

    class SfxOrganizeDlg_Impl *pImp;

//  virtual void    DataChanged( const DataChangedEvent& rDCEvt );
public:
    SfxTemplateOrganizeDlg(Window * pParent, SfxDocumentTemplates* = 0);
    ~SfxTemplateOrganizeDlg();

#define RET_EDIT_STYLE       100

    virtual short Execute();
};

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

#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif

#include "objsh.hxx"
#include "orgmgr.hxx"

//=========================================================================

class SfxDocumentTemplates;
class Path;

//=========================================================================

#ifndef _SFX_HXX

class SfxOrganizeDlg_Impl;

class SfxOrganizeListBox_Impl : public SvTreeListBox
{
    enum BMPTYPE            { BMPTYPE_FOLDER, BMPTYPE_DOC };

friend class SfxOrganizeDlg_Impl;

    Image                   aOpenedFolderBmp;
    Image                   aClosedFolderBmp;
    Image                   aOpenedDocBmp;
    Image                   aClosedDocBmp;

    Image                   aOpenedFolderBmpHC;
    Image                   aClosedFolderBmpHC;
    Image                   aOpenedDocBmpHC;
    Image                   aClosedDocBmpHC;

    SfxOrganizeMgr*         pMgr;
    SfxOrganizeDlg_Impl*    pDlg;

    static BOOL             bDropMoveOk;

    DECL_LINK( OnAsyncExecuteDrop, ExecuteDropEvent* );

protected:
    virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection & );
    virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText );
    virtual BOOL NotifyMoving(SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent, ULONG &);
    virtual BOOL NotifyCopying(SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent, ULONG &);
    virtual void RequestingChilds( SvLBoxEntry* pParent );
    virtual long ExpandingHdl();
    virtual BOOL Select( SvLBoxEntry* pEntry, BOOL bSelect=TRUE );

    // new d&d
    virtual DragDropMode    NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* );
    virtual BOOL            NotifyAcceptDrop( SvLBoxEntry* );
    virtual sal_Int8        AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8        ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void            DragFinished( sal_Int8 nDropAction );

public:
    enum DataEnum   { VIEW_TEMPLATES, VIEW_FILES } eViewType;

    SfxOrganizeListBox_Impl( SfxOrganizeDlg_Impl* pDlg, Window* pParent, WinBits, DataEnum );

    DataEnum    GetViewType() const { return eViewType; }
    void        SetViewType(DataEnum eType) { eViewType = eType; }

    void SetMgr(SfxOrganizeMgr *pM) { pMgr = pM; }
    void Reset();
    inline void SetBitmaps(
                    const Image &rOFolderBmp, const Image &rCFolderBmp, const Image &rODocBmp, const Image &rCDocBmp,
                    const Image &rOFolderBmpHC, const Image &rCFolderBmpHC, const Image &rODocBmpHC, const Image &rCDocBmpHC );
    const Image &GetClosedBmp(USHORT nLevel) const;
    const Image &GetOpenedBmp(USHORT nLevel) const;

    virtual PopupMenu*  CreateContextMenu();

private:
    BOOL IsStandard_Impl( SvLBoxEntry *) const;
    BOOL MoveOrCopyTemplates(SvLBox *pSourceBox,
                            SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent,
                            ULONG &rIdx,
                            BOOL bCopy);
    BOOL MoveOrCopyContents(SvLBox *pSourceBox,
                            SvLBoxEntry *pSource,
                            SvLBoxEntry* pTarget,
                            SvLBoxEntry *&pNewParent,
                            ULONG &rIdx,
                            BOOL bCopy);
    inline USHORT       GetDocLevel() const;
    SfxObjectShellRef   GetObjectShell( const Path& );
    BOOL                IsUniqName_Impl( const String &rText,
                                         SvLBoxEntry* pParent, SvLBoxEntry* pEntry = 0 ) const;
    USHORT              GetLevelCount_Impl( SvLBoxEntry* pParent ) const;

    SvLBoxEntry*        InsertEntryByBmpType( const XubString& rText, BMPTYPE eBmpType,
                            SvLBoxEntry* pParent = NULL, BOOL bChildsOnDemand = FALSE,
                            ULONG nPos = LIST_APPEND, void* pUserData = NULL );
};

#endif // _SFX_HXX

//=========================================================================

class SfxTemplateOrganizeDlg : public ModalDialog
{
friend class SfxOrganizeListBox_Impl;

    class SfxOrganizeDlg_Impl *pImp;

//  virtual void    DataChanged( const DataChangedEvent& rDCEvt );
public:
    SfxTemplateOrganizeDlg(Window * pParent, SfxDocumentTemplates* = 0);
    ~SfxTemplateOrganizeDlg();

#define RET_EDIT_STYLE       100

    virtual short Execute();
};

#endif
<|endoftext|>