<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/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script didn't run.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result);
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script ran.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result);
  EXPECT_TRUE(result);
}

// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
#if defined(OS_CHROMEOS)
// Hanging on ChromeOS: http://crbug.com/53991
#define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode
#else
#define MAYBE_IncognitoSplitMode IncognitoSplitMode
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
// Hangy, http://crbug.com/53869.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* incognito_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Disable IncognitoSplitMode for linux, it's hanging there too.<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/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/browser_action_test_util.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script didn't run.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'Unmodified')",
      &result);
  EXPECT_TRUE(result);
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // Load a dummy extension. This just tests that we don't regress a
  // crash fix when multiple incognito- and non-incognito-enabled extensions
  // are mixed.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("all_frames")));

  // Loads a simple extension which attempts to change the title of every page
  // that loads to "modified".
  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("incognito").AppendASCII("content_scripts")));

  // Dummy extension #2.
  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("api_test")
      .AppendASCII("content_scripts").AppendASCII("isolated_world1")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* otr_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);
  TabContents* tab = otr_browser->GetSelectedTabContents();

  // Verify the script ran.
  bool result = false;
  ui_test_utils::ExecuteJavaScriptAndExtractBool(
      tab->render_view_host(), L"",
      L"window.domAutomationController.send(document.title == 'modified')",
      &result);
  EXPECT_TRUE(result);
}

// Tests that the APIs in an incognito-enabled extension work properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-enabled split-mode extension work
// properly.
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
// Hanging on ChromeOS and linux: http://crbug.com/53991
#define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode
#else
#define MAYBE_IncognitoSplitMode IncognitoSplitMode
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  // We need 2 ResultCatchers because we'll be running the same test in both
  // regular and incognito mode.
  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  ResultCatcher catcher_incognito;
  catcher_incognito.RestrictToProfile(
      browser()->profile()->GetOffTheRecordProfile());

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("split")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
  EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();
}

// Tests that the APIs in an incognito-disabled extension don't see incognito
// events or callbacks.
// Hangy, http://crbug.com/53869.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));

  ASSERT_TRUE(LoadExtension(test_data_dir_
      .AppendASCII("incognito").AppendASCII("apis_disabled")));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// Test that opening a popup from an incognito browser window works properly.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {
  host_resolver()->AddRule("*", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  ResultCatcher catcher;

  ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_
      .AppendASCII("incognito").AppendASCII("popup")));

  // Open incognito window and navigate to test page.
  ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
      GURL("http://www.example.com:1337/files/extensions/test_file.html"));
  Browser* incognito_browser = BrowserList::FindBrowserWithType(
      browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,
      false);

  // Simulate the incognito's browser action being clicked.
  BrowserActionTestUtil(incognito_browser).Press(0);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"

// Sometimes times out on Mac OS
// crbug.com/
#ifdef OS_MACOSX
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Processes) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Processes) {
#endif
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("processes/api")) << message_;
}

// http://crbug.com/111787
#ifdef OS_WIN
#define MAYBE_ProcessesVsTaskManager DISABLED_ProcessesVsTaskManager
#else
#define MAYBE_ProcessesVsTaskManager ProcessesVsTaskManager
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_ProcessesVsTaskManager) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  // Ensure task manager is not yet updating
  TaskManagerModel* model = TaskManager::GetInstance()->model();
  EXPECT_EQ(0, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::IDLE, model->update_state_);

  // Load extension that adds listener in background page
  ExtensionTestMessageListener listener("ready", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("processes").AppendASCII("onupdated")));
  ASSERT_TRUE(listener.WaitUntilSatisfied());

  // Ensure the task manager has started updating
  EXPECT_EQ(1, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Now show the task manager and wait for it to be ready
  TaskManagerBrowserTestUtil::ShowTaskManagerAndWaitForReady(browser());

  EXPECT_EQ(2, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Unload the extension and check that listener count decreases
  UnloadExtension(last_loaded_extension_id_);
  EXPECT_EQ(1, model->update_requests_);
}
<commit_msg>Re-enabling browser_tests:ExtensionApiTest.ProcessesVsTaskManager.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_switches.h"

// Sometimes times out on Mac OS
// crbug.com/
#ifdef OS_MACOSX
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Processes) {
#else
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Processes) {
#endif
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("processes/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ProcessesVsTaskManager) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  // Ensure task manager is not yet updating
  TaskManagerModel* model = TaskManager::GetInstance()->model();
  EXPECT_EQ(0, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::IDLE, model->update_state_);

  // Load extension that adds listener in background page
  ExtensionTestMessageListener listener("ready", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("processes").AppendASCII("onupdated")));
  ASSERT_TRUE(listener.WaitUntilSatisfied());

  // Ensure the task manager has started updating
  EXPECT_EQ(1, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Now show the task manager and wait for it to be ready
  TaskManagerBrowserTestUtil::ShowTaskManagerAndWaitForReady(browser());

  EXPECT_EQ(2, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Unload the extension and check that listener count decreases
  UnloadExtension(last_loaded_extension_id_);
  EXPECT_EQ(1, model->update_requests_);
}
<|endoftext|>


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

#include "chrome/browser/printing/print_preview_message_handler.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_preview_tab_controller.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "chrome/common/content_restriction.h"
#include "chrome/common/print_messages.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"

namespace printing {

PrintPreviewMessageHandler::PrintPreviewMessageHandler(
    TabContents* tab_contents)
    : TabContentsObserver(tab_contents) {
  DCHECK(tab_contents);
}

PrintPreviewMessageHandler::~PrintPreviewMessageHandler() {
}

TabContents* PrintPreviewMessageHandler::GetPrintPreviewTab() {
  // Get/Create preview tab for initiator tab.
  printing::PrintPreviewTabController* tab_controller =
      printing::PrintPreviewTabController::GetInstance();
  if (!tab_controller)
    return NULL;
  return tab_controller->GetPrintPreviewForTab(tab_contents());
}

void PrintPreviewMessageHandler::OnPagesReadyForPreview(
    const PrintHostMsg_DidPreviewDocument_Params& params) {
  // Always need to stop the worker and send PrintMsg_PrintingDone.
  PrintJobManager* print_job_manager = g_browser_process->print_job_manager();
  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager->PopPrinterQuery(params.document_cookie, &printer_query);
  if (printer_query.get()) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        NewRunnableMethod(printer_query.get(),
                          &printing::PrinterQuery::StopWorker));
  }

  RenderViewHost* rvh = tab_contents()->render_view_host();
  rvh->Send(new PrintMsg_PrintingDone(rvh->routing_id(),
                                     params.document_cookie,
                                     true));

  // Get the print preview tab.
  TabContents* print_preview_tab = GetPrintPreviewTab();
  // User might have closed it already.
  if (!print_preview_tab)
    return;

#if defined(OS_POSIX)
  base::SharedMemory* shared_buf =
      new base::SharedMemory(params.metafile_data_handle, true);
  if (!shared_buf->Map(params.data_size)) {
    NOTREACHED();
    delete shared_buf;
    return;
  }

  PrintPreviewUI* print_preview_ui =
      static_cast<PrintPreviewUI*>(print_preview_tab->web_ui());
  PrintPreviewUIHTMLSource* html_source = print_preview_ui->html_source();
  html_source->SetPrintPreviewData(
      std::make_pair(shared_buf, params.data_size));
  print_preview_ui->PreviewDataIsAvailable(params.expected_pages_count,
                                           tab_contents()->GetTitle());
#endif  // defined(OS_POSIX)
}

void PrintPreviewMessageHandler::OnPrintPreviewNodeUnderContextMenu() {
  PrintPreviewTabController::PrintPreview(tab_contents());
}

void PrintPreviewMessageHandler::OnScriptInitiatedPrintPreview() {
  PrintPreviewTabController::PrintPreview(tab_contents());
}

bool PrintPreviewMessageHandler::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
    IPC_MESSAGE_HANDLER(PrintHostMsg_PagesReadyForPreview,
                        OnPagesReadyForPreview)
    IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewNodeUnderContextMenu,
                        OnPrintPreviewNodeUnderContextMenu)
    IPC_MESSAGE_HANDLER(PrintHostMsg_ScriptInitiatedPrintPreview,
                        OnScriptInitiatedPrintPreview)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PrintPreviewMessageHandler::DidStartLoading() {
  if (tab_contents()->delegate() &&
      printing::PrintPreviewTabController::IsPrintPreviewTab(tab_contents())) {
    tab_contents()->SetContentRestrictions(CONTENT_RESTRICTION_PRINT);
  }
}

}  // namespace printing
<commit_msg>Remove #if defined(OS_POSIX) so code can be used in windows print preview.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/printing/print_preview_message_handler.h"

#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_preview_tab_controller.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "chrome/common/content_restriction.h"
#include "chrome/common/print_messages.h"
#include "content/browser/browser_thread.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"

namespace printing {

PrintPreviewMessageHandler::PrintPreviewMessageHandler(
    TabContents* tab_contents)
    : TabContentsObserver(tab_contents) {
  DCHECK(tab_contents);
}

PrintPreviewMessageHandler::~PrintPreviewMessageHandler() {
}

TabContents* PrintPreviewMessageHandler::GetPrintPreviewTab() {
  // Get/Create preview tab for initiator tab.
  printing::PrintPreviewTabController* tab_controller =
      printing::PrintPreviewTabController::GetInstance();
  if (!tab_controller)
    return NULL;
  return tab_controller->GetPrintPreviewForTab(tab_contents());
}

void PrintPreviewMessageHandler::OnPagesReadyForPreview(
    const PrintHostMsg_DidPreviewDocument_Params& params) {
  // Always need to stop the worker and send PrintMsg_PrintingDone.
  PrintJobManager* print_job_manager = g_browser_process->print_job_manager();
  scoped_refptr<printing::PrinterQuery> printer_query;
  print_job_manager->PopPrinterQuery(params.document_cookie, &printer_query);
  if (printer_query.get()) {
    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        NewRunnableMethod(printer_query.get(),
                          &printing::PrinterQuery::StopWorker));
  }

  RenderViewHost* rvh = tab_contents()->render_view_host();
  rvh->Send(new PrintMsg_PrintingDone(rvh->routing_id(),
                                     params.document_cookie,
                                     true));

  // Get the print preview tab.
  TabContents* print_preview_tab = GetPrintPreviewTab();
  // User might have closed it already.
  if (!print_preview_tab)
    return;

  base::SharedMemory* shared_buf =
      new base::SharedMemory(params.metafile_data_handle, true);
  if (!shared_buf->Map(params.data_size)) {
    NOTREACHED();
    delete shared_buf;
    return;
  }

  PrintPreviewUI* print_preview_ui =
      static_cast<PrintPreviewUI*>(print_preview_tab->web_ui());
  PrintPreviewUIHTMLSource* html_source = print_preview_ui->html_source();
  html_source->SetPrintPreviewData(
      std::make_pair(shared_buf, params.data_size));
  print_preview_ui->PreviewDataIsAvailable(params.expected_pages_count,
                                           tab_contents()->GetTitle());
}

void PrintPreviewMessageHandler::OnPrintPreviewNodeUnderContextMenu() {
  PrintPreviewTabController::PrintPreview(tab_contents());
}

void PrintPreviewMessageHandler::OnScriptInitiatedPrintPreview() {
  PrintPreviewTabController::PrintPreview(tab_contents());
}

bool PrintPreviewMessageHandler::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
    IPC_MESSAGE_HANDLER(PrintHostMsg_PagesReadyForPreview,
                        OnPagesReadyForPreview)
    IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewNodeUnderContextMenu,
                        OnPrintPreviewNodeUnderContextMenu)
    IPC_MESSAGE_HANDLER(PrintHostMsg_ScriptInitiatedPrintPreview,
                        OnScriptInitiatedPrintPreview)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PrintPreviewMessageHandler::DidStartLoading() {
  if (tab_contents()->delegate() &&
      printing::PrintPreviewTabController::IsPrintPreviewTab(tab_contents())) {
    tab_contents()->SetContentRestrictions(CONTENT_RESTRICTION_PRINT);
  }
}

}  // namespace printing
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "abstractmediaproducer.h"
#include "abstractmediaproducer_p.h"
#include "factory.h"

#include "videopath.h"
#include "audiopath.h"

#include "mediaproducerinterface.h"
#include "addoninterface.h"
#include "trackinterface.h"
#include "chapterinterface.h"

#include <QTimer>

#include <kdebug.h>
#include <QStringList>

#include "frontendinterface_p.h"
#include "navigationinterface.h"
#include "angleinterface.h"

#define PHONON_CLASSNAME AbstractMediaProducer
#define PHONON_INTERFACENAME MediaProducerInterface

namespace Phonon
{
PHONON_ABSTRACTBASE_IMPL

AbstractMediaProducer::~AbstractMediaProducer()
{
    K_D(AbstractMediaProducer);
    if (d->backendObject) {
        switch (state()) {
            case PlayingState:
            case BufferingState:
            case PausedState:
                stop();
                break;
            case ErrorState:
            case StoppedState:
            case LoadingState:
                break;
        }
    }
    foreach(VideoPath* vp, d->videoPaths)
        d->removeDestructionHandler(vp, d);
    foreach(AudioPath* ap, d->audioPaths)
        d->removeDestructionHandler(ap, d);
}

bool AbstractMediaProducer::addVideoPath( VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( d->videoPaths.contains( videoPath ) )
		return false;

	if( iface() )
	{
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) )
		{
            d->addDestructionHandler(videoPath, d);
			d->videoPaths.append( videoPath );
			return true;
		}
	}
	return false;
}

bool AbstractMediaProducer::addAudioPath( AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( d->audioPaths.contains( audioPath ) )
		return false;

	if( iface() )
	{
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) )
		{
            d->addDestructionHandler(audioPath, d);
			d->audioPaths.append( audioPath );
			return true;
		}
	}
	return false;
}

Phonon::State AbstractMediaProducer::state() const
{
    K_D(const AbstractMediaProducer);
    if (!d->backendObject || d->errorOverride) {
        return d->state;
    }
    return INTERFACE_CALL(state());
}

PHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 )
PHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval )
PHONON_INTERFACE_GETTER( bool, hasVideo, false )
PHONON_INTERFACE_GETTER( bool, isSeekable, false )
PHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime )
PHONON_INTERFACE_GETTER1( QString, selectedAudioStream,    d->selectedAudioStream[    audioPath ], AudioPath*, audioPath )
PHONON_INTERFACE_GETTER1( QString, selectedVideoStream,    d->selectedVideoStream[    videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() )

void AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectAudioStream(streamName, audioPath->iface()));
	else
		d->selectedAudioStream[ audioPath ] = streamName;
}

void AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectVideoStream(streamName, videoPath->iface()));
	else
		d->selectedVideoStream[ videoPath ] = streamName;
}

void AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(selectSubtitleStream(streamName, videoPath->iface()));
	else
		d->selectedSubtitleStream[ videoPath ] = streamName;
}

QList<VideoPath*> AbstractMediaProducer::videoPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->videoPaths;
}

QList<AudioPath*> AbstractMediaProducer::audioPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->audioPaths;
}

void AbstractMediaProducer::play()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(play());
}

void AbstractMediaProducer::pause()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(pause());
}

void AbstractMediaProducer::stop()
{
	K_D( AbstractMediaProducer );
	if( iface() )
	{
        INTERFACE_CALL(stop());
	}
}

void AbstractMediaProducer::seek( qint64 time )
{
	K_D( AbstractMediaProducer );
	State s = state();
	if( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) )
        INTERFACE_CALL(seek(time));
}

QString AbstractMediaProducer::errorString() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        if (d->errorOverride) {
            return d->errorString;
        }
        return INTERFACE_CALL(errorString());
    }
    return QString();
}

ErrorType AbstractMediaProducer::errorType() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        if (d->errorOverride) {
            return d->errorType;
        }
        return INTERFACE_CALL(errorType());
    }
    return Phonon::NoError;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<TrackInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::TrackInterface);
    }
    return false;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<ChapterInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::ChapterInterface);
    }
    return false;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<NavigationInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::NavigationInterface);
    }
    return false;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<AngleInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::AngleInterface);
    }
    return false;
}

bool AbstractMediaProducerPrivate::aboutToDeleteIface()
{
	//kDebug( 600 ) << k_funcinfo << endl;
	if( backendObject )
	{
        state = pINTERFACE_CALL(state());
        currentTime = pINTERFACE_CALL(currentTime());
        tickInterval = pINTERFACE_CALL(tickInterval());
	}
	return true;
}

void AbstractMediaProducer::setupIface()
{
	K_D( AbstractMediaProducer );
	Q_ASSERT( d->backendObject );
	//kDebug( 600 ) << k_funcinfo << endl;

	connect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) );
	connect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) );
	connect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) );
    connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));
    connect(d->backendObject, SIGNAL(hasVideoChanged(bool)), SIGNAL(hasVideoChanged(bool)));
    connect(d->backendObject, SIGNAL(bufferStatus(int)), SIGNAL(bufferStatus(int)));

	// set up attributes
    INTERFACE_CALL(setTickInterval(d->tickInterval));

	foreach( AudioPath* a, d->audioPaths )
	{
		if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) )
			d->audioPaths.removeAll( a );
	}
	foreach( VideoPath* v, d->videoPaths )
	{
		if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) )
			d->videoPaths.removeAll( v );
	}

	switch( d->state )
	{
		case LoadingState:
		case StoppedState:
		case ErrorState:
			break;
		case PlayingState:
		case BufferingState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) );
			break;
		case PausedState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePause() ) );
			break;
	}
    const State backendState = INTERFACE_CALL(state());
    if (d->state != backendState && d->state != ErrorState) {
        // careful: if d->state is ErrorState we might be switching from a
        // MediaObject to a ByteStream for KIO fallback. In that case the state
        // change to ErrorState was already suppressed.
        kDebug(600) << "emitting a state change because the backend object has been replaced" << endl;
        emit stateChanged(backendState, d->state);
        d->state = backendState;
    }

    foreach (FrontendInterfacePrivate *f, d->interfaceList) {
        f->_backendObjectChanged();
    }
}

void AbstractMediaProducerPrivate::_k_resumePlay()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
}

void AbstractMediaProducerPrivate::_k_resumePause()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
	qobject_cast<MediaProducerInterface*>( backendObject )->pause();
}

void AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData )
{
	metaData = newMetaData;
	emit q_func()->metaDataChanged();
}

QStringList AbstractMediaProducer::metaDataKeys() const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.keys();
}

QStringList AbstractMediaProducer::metaDataItems( const QString& key ) const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.values( key );
}

void AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o )
{
	// this method is called from Phonon::Base::~Base(), meaning the AudioPath
	// dtor has already been called, also virtual functions don't work anymore
	// (therefore qobject_cast can only downcast from Base)
	Q_ASSERT( o );
	AudioPath* audioPath = static_cast<AudioPath*>( o );
	VideoPath* videoPath = static_cast<VideoPath*>( o );
	if( audioPaths.contains( audioPath ) )
	{
		if( backendObject )
			qobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() );
		audioPaths.removeAll( audioPath );
	}
	else if( videoPaths.contains( videoPath ) )
	{
		if( backendObject )
			qobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() );
		videoPaths.removeAll( videoPath );
	}
}

} //namespace Phonon

#include "abstractmediaproducer.moc"
#undef PHONON_CLASSNAME
#undef PHONON_INTERFACENAME
// vim: sw=4 ts=4 tw=80
<commit_msg>don't call the backend for invalid frontend objects (a frontend object is !isValid() if there's no backend object, and none can be created)<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "abstractmediaproducer.h"
#include "abstractmediaproducer_p.h"
#include "factory.h"

#include "videopath.h"
#include "audiopath.h"

#include "mediaproducerinterface.h"
#include "addoninterface.h"
#include "trackinterface.h"
#include "chapterinterface.h"

#include <QTimer>

#include <kdebug.h>
#include <QStringList>

#include "frontendinterface_p.h"
#include "navigationinterface.h"
#include "angleinterface.h"

#define PHONON_CLASSNAME AbstractMediaProducer
#define PHONON_INTERFACENAME MediaProducerInterface

namespace Phonon
{
PHONON_ABSTRACTBASE_IMPL

AbstractMediaProducer::~AbstractMediaProducer()
{
    K_D(AbstractMediaProducer);
    if (d->backendObject) {
        switch (state()) {
            case PlayingState:
            case BufferingState:
            case PausedState:
                stop();
                break;
            case ErrorState:
            case StoppedState:
            case LoadingState:
                break;
        }
    }
    foreach(VideoPath* vp, d->videoPaths)
        d->removeDestructionHandler(vp, d);
    foreach(AudioPath* ap, d->audioPaths)
        d->removeDestructionHandler(ap, d);
}

bool AbstractMediaProducer::addVideoPath( VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
	if( d->videoPaths.contains( videoPath ) )
		return false;

    if (iface() && videoPath->iface()) {
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) )
		{
            d->addDestructionHandler(videoPath, d);
			d->videoPaths.append( videoPath );
			return true;
		}
	}
	return false;
}

bool AbstractMediaProducer::addAudioPath( AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
	if( d->audioPaths.contains( audioPath ) )
		return false;

    if (iface() && audioPath->iface()) {
		if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) )
		{
            d->addDestructionHandler(audioPath, d);
			d->audioPaths.append( audioPath );
			return true;
		}
	}
	return false;
}

Phonon::State AbstractMediaProducer::state() const
{
    K_D(const AbstractMediaProducer);
    if (!d->backendObject || d->errorOverride) {
        return d->state;
    }
    return INTERFACE_CALL(state());
}

PHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 )
PHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval )
PHONON_INTERFACE_GETTER( bool, hasVideo, false )
PHONON_INTERFACE_GETTER( bool, isSeekable, false )
PHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime )
PHONON_INTERFACE_GETTER1( QString, selectedAudioStream,    d->selectedAudioStream[    audioPath ], AudioPath*, audioPath )
PHONON_INTERFACE_GETTER1( QString, selectedVideoStream,    d->selectedVideoStream[    videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath )
PHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() )
PHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() )

void AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath )
{
	K_D( AbstractMediaProducer );
    if (iface() && audioPath->iface()) {
        INTERFACE_CALL(selectAudioStream(streamName, audioPath->iface()));
    } else {
		d->selectedAudioStream[ audioPath ] = streamName;
    }
}

void AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
    if (iface() && videoPath->iface()) {
        INTERFACE_CALL(selectVideoStream(streamName, videoPath->iface()));
    } else {
		d->selectedVideoStream[ videoPath ] = streamName;
    }
}

void AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath )
{
	K_D( AbstractMediaProducer );
    if (iface() && videoPath->iface()) {
        INTERFACE_CALL(selectSubtitleStream(streamName, videoPath->iface()));
    } else {
		d->selectedSubtitleStream[ videoPath ] = streamName;
    }
}

QList<VideoPath*> AbstractMediaProducer::videoPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->videoPaths;
}

QList<AudioPath*> AbstractMediaProducer::audioPaths() const
{
	K_D( const AbstractMediaProducer );
	return d->audioPaths;
}

void AbstractMediaProducer::play()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(play());
}

void AbstractMediaProducer::pause()
{
	K_D( AbstractMediaProducer );
	if( iface() )
        INTERFACE_CALL(pause());
}

void AbstractMediaProducer::stop()
{
	K_D( AbstractMediaProducer );
	if( iface() )
	{
        INTERFACE_CALL(stop());
	}
}

void AbstractMediaProducer::seek( qint64 time )
{
	K_D( AbstractMediaProducer );
	State s = state();
	if( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) )
        INTERFACE_CALL(seek(time));
}

QString AbstractMediaProducer::errorString() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        if (d->errorOverride) {
            return d->errorString;
        }
        return INTERFACE_CALL(errorString());
    }
    return QString();
}

ErrorType AbstractMediaProducer::errorType() const
{
    if (state() == Phonon::ErrorState) {
        K_D(const AbstractMediaProducer);
        if (d->errorOverride) {
            return d->errorType;
        }
        return INTERFACE_CALL(errorType());
    }
    return Phonon::NoError;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<TrackInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::TrackInterface);
    }
    return false;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<ChapterInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::ChapterInterface);
    }
    return false;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<NavigationInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::NavigationInterface);
    }
    return false;
}

template<>
PHONONCORE_EXPORT
bool AbstractMediaProducer::hasInterface<AngleInterface>() const
{
    K_D(const AbstractMediaProducer);
    if (d->backendObject) {
        return qobject_cast<AddonInterface *>(d->backendObject)
            ->hasInterface(AddonInterface::AngleInterface);
    }
    return false;
}

bool AbstractMediaProducerPrivate::aboutToDeleteIface()
{
	//kDebug( 600 ) << k_funcinfo << endl;
	if( backendObject )
	{
        state = pINTERFACE_CALL(state());
        currentTime = pINTERFACE_CALL(currentTime());
        tickInterval = pINTERFACE_CALL(tickInterval());
	}
	return true;
}

void AbstractMediaProducer::setupIface()
{
	K_D( AbstractMediaProducer );
	Q_ASSERT( d->backendObject );
	//kDebug( 600 ) << k_funcinfo << endl;

	connect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) );
	connect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) );
	connect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) );
    connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));
    connect(d->backendObject, SIGNAL(hasVideoChanged(bool)), SIGNAL(hasVideoChanged(bool)));
    connect(d->backendObject, SIGNAL(bufferStatus(int)), SIGNAL(bufferStatus(int)));

	// set up attributes
    INTERFACE_CALL(setTickInterval(d->tickInterval));

	foreach( AudioPath* a, d->audioPaths )
	{
        if (!a->iface() || !INTERFACE_CALL(addAudioPath(a->iface()))) {
			d->audioPaths.removeAll( a );
        }
	}
	foreach( VideoPath* v, d->videoPaths )
	{
        if (!v->iface() || !INTERFACE_CALL(addVideoPath(v->iface()))) {
			d->videoPaths.removeAll( v );
        }
	}

	switch( d->state )
	{
		case LoadingState:
		case StoppedState:
		case ErrorState:
			break;
		case PlayingState:
		case BufferingState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) );
			break;
		case PausedState:
			QTimer::singleShot( 0, this, SLOT( _k_resumePause() ) );
			break;
	}
    const State backendState = INTERFACE_CALL(state());
    if (d->state != backendState && d->state != ErrorState) {
        // careful: if d->state is ErrorState we might be switching from a
        // MediaObject to a ByteStream for KIO fallback. In that case the state
        // change to ErrorState was already suppressed.
        kDebug(600) << "emitting a state change because the backend object has been replaced" << endl;
        emit stateChanged(backendState, d->state);
        d->state = backendState;
    }

    foreach (FrontendInterfacePrivate *f, d->interfaceList) {
        f->_backendObjectChanged();
    }
}

void AbstractMediaProducerPrivate::_k_resumePlay()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
}

void AbstractMediaProducerPrivate::_k_resumePause()
{
	qobject_cast<MediaProducerInterface*>( backendObject )->play();
	if( currentTime > 0 )
		qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );
	qobject_cast<MediaProducerInterface*>( backendObject )->pause();
}

void AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData )
{
	metaData = newMetaData;
	emit q_func()->metaDataChanged();
}

QStringList AbstractMediaProducer::metaDataKeys() const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.keys();
}

QStringList AbstractMediaProducer::metaDataItems( const QString& key ) const
{
	K_D( const AbstractMediaProducer );
	return d->metaData.values( key );
}

void AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o )
{
	// this method is called from Phonon::Base::~Base(), meaning the AudioPath
	// dtor has already been called, also virtual functions don't work anymore
	// (therefore qobject_cast can only downcast from Base)
	Q_ASSERT( o );
	AudioPath* audioPath = static_cast<AudioPath*>( o );
	VideoPath* videoPath = static_cast<VideoPath*>( o );
	if( audioPaths.contains( audioPath ) )
	{
        if (backendObject && audioPath->iface()) {
            pINTERFACE_CALL(removeAudioPath(audioPath->iface()));
        }
		audioPaths.removeAll( audioPath );
	}
	else if( videoPaths.contains( videoPath ) )
	{
        if (backendObject && videoPath->iface()) {
            pINTERFACE_CALL(removeVideoPath(videoPath->iface()));
        }
		videoPaths.removeAll( videoPath );
	}
}

} //namespace Phonon

#include "abstractmediaproducer.moc"
#undef PHONON_CLASSNAME
#undef PHONON_INTERFACENAME
// vim: sw=4 ts=4 tw=80
<|endoftext|>


<commit_before><commit_msg>Don't run SingleProcessMemoryTracingTest on Google Chrome builds<commit_after><|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/browser/translate/translate_infobars_delegates.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// TranslateInfoBarDelegate: InfoBarDelegate overrides: ------------------------

SkBitmap* TranslateInfoBarDelegate::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_TRANSLATE);
}

bool TranslateInfoBarDelegate::EqualsDelegate(InfoBarDelegate* delegate) const {
  TranslateInfoBarDelegate* translate_delegate =
      delegate->AsTranslateInfoBarDelegate();
  // There can be only 1 translate infobar at any one time.
  return (!!translate_delegate);
}

void TranslateInfoBarDelegate::InfoBarClosed() {
  delete this;
}

// TranslateInfoBarDelegate: public: -------------------------------------------

void TranslateInfoBarDelegate::ModifyOriginalLanguage(
    const std::string& original_language) {
  original_language_ = original_language;
  // TODO(kuan): Send stats to Google Translate that original language has been
  // modified.
}

void TranslateInfoBarDelegate::ModifyTargetLanguage(
    const std::string& target_language) {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::GetAvailableOriginalLanguages(
    std::vector<std::string>* languages) {
  // TODO(kuan): Call backend when it's ready; hardcode a list for now.
  languages->push_back("Arabic");
  languages->push_back("Bengali");
  languages->push_back("Bulgarian");
  languages->push_back("Chinese (Simplified Han)");
  languages->push_back("Chinese (Traditional Han)");
  languages->push_back("Croatian");
  languages->push_back("Czech");
  languages->push_back("Danish");
  languages->push_back("Dutch");
  languages->push_back("English");
  languages->push_back("Estonian");
  languages->push_back("Filipino");
  languages->push_back("Finnish");
  languages->push_back("French");
  languages->push_back("German");
  languages->push_back("Greek");
  languages->push_back("Hebrew");
  languages->push_back("Hindi");
  languages->push_back("Hungarian");
  languages->push_back("Indonesian");
  languages->push_back("Italian");
  languages->push_back("Japanese");
  languages->push_back("Korean");
  languages->push_back("Latvian");
  languages->push_back("Lithuanian");
  languages->push_back("Norwegian");
  languages->push_back("Polish");
  languages->push_back("Portuguese");
  languages->push_back("Romanian");
  languages->push_back("Russian");
  languages->push_back("Serbian");
  languages->push_back("Slovak");
  languages->push_back("Slovenian");
  languages->push_back("Spanish");
  languages->push_back("Swedish");
  languages->push_back("Tamil");
  languages->push_back("Thai");
  languages->push_back("Turkish");
  languages->push_back("Ukrainian");
  languages->push_back("Vietnamese");
}

void TranslateInfoBarDelegate::GetAvailableTargetLanguages(
    std::vector<std::string>* languages) {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::Translate() {
  // TODO(kuan): Call actual Translate method.
/*
  Translate(WideToUTF8(original_language()), WideToUTF8(target_language()));
*/
}

bool TranslateInfoBarDelegate::IsLanguageBlacklisted() {
  NOTREACHED() << "Subclass should override";
  return false;
}

bool TranslateInfoBarDelegate::IsSiteBlacklisted() {
  NOTREACHED() << "Subclass should override";
  return false;
}

bool TranslateInfoBarDelegate::ShouldAlwaysTranslate() {
  NOTREACHED() << "Subclass should override";
  return false;
}

void TranslateInfoBarDelegate::ToggleLanguageBlacklist() {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::ToggleSiteBlacklist() {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::ToggleAlwaysTranslate() {
  NOTREACHED() << "Subclass should override";
}

// TranslateInfoBarDelegate: protected: ----------------------------------------

TranslateInfoBarDelegate::TranslateInfoBarDelegate(TabContents* tab_contents,
    PrefService* user_prefs, const std::string& original_language,
    const std::string& target_language)
    : InfoBarDelegate(tab_contents),
      tab_contents_(tab_contents),
      original_language_(original_language),
      target_language_(target_language),
      prefs_(user_prefs) {
}

// BeforeTranslateInfoBarDelegate: public: -------------------------------------

BeforeTranslateInfoBarDelegate::BeforeTranslateInfoBarDelegate(
    TabContents* tab_contents, PrefService* user_prefs, const GURL& url,
    const std::string& original_language, const std::string& target_language)
    : TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
          target_language),
      site_(url.HostNoBrackets()),
      never_translate_language_(false),
      never_translate_site_(false) {
}

bool BeforeTranslateInfoBarDelegate::IsLanguageBlacklisted() {
  never_translate_language_ =
    prefs_.IsLanguageBlacklisted(original_language());
  return never_translate_language_;
}

void BeforeTranslateInfoBarDelegate::ToggleLanguageBlacklist() {
  never_translate_language_ = !never_translate_language_;
  if (never_translate_language_)
    prefs_.BlacklistLanguage(original_language());
  else
    prefs_.RemoveLanguageFromBlacklist(original_language());
}

bool BeforeTranslateInfoBarDelegate::IsSiteBlacklisted() {
  never_translate_site_ = prefs_.IsSiteBlacklisted(site_);
  return never_translate_site_;
}

void BeforeTranslateInfoBarDelegate::ToggleSiteBlacklist() {
  never_translate_site_ = !never_translate_site_;
  if (never_translate_site_)
    prefs_.BlacklistSite(site_);
  else
    prefs_.RemoveSiteFromBlacklist(site_);
}

// AfterTranslateInfoBarDelegate: public: --------------------------------------

AfterTranslateInfoBarDelegate::AfterTranslateInfoBarDelegate(
    TabContents* tab_contents, PrefService* user_prefs,
    const std::string& original_language, const std::string& target_language)
    : TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
          target_language),
      always_translate_(false) {
}

void AfterTranslateInfoBarDelegate::GetAvailableTargetLanguages(
    std::vector<std::string>* languages) {
  // TODO(kuan): Call backend when it's ready; hardcode a list for now.
  GetAvailableOriginalLanguages(languages);
}

void AfterTranslateInfoBarDelegate::ModifyTargetLanguage(
    const std::string& target_language) {
  target_language_ = target_language;
}

bool AfterTranslateInfoBarDelegate::ShouldAlwaysTranslate() {
  always_translate_ = prefs_.IsLanguagePairWhitelisted(original_language(),
      target_language());
  return always_translate_;
}

void AfterTranslateInfoBarDelegate::ToggleAlwaysTranslate() {
  always_translate_ = !always_translate_;
  if (always_translate_)
    prefs_.WhitelistLanguagePair(original_language(), target_language());
  else
    prefs_.RemoveLanguagePairFromWhitelist(original_language(),
        target_language());
}
<commit_msg>use stubs for yet-to-be-implemented non-windows translate infobars<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/browser/translate/translate_infobars_delegates.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// TranslateInfoBarDelegate: InfoBarDelegate overrides: ------------------------

SkBitmap* TranslateInfoBarDelegate::GetIcon() const {
  return ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_INFOBAR_TRANSLATE);
}

bool TranslateInfoBarDelegate::EqualsDelegate(InfoBarDelegate* delegate) const {
  TranslateInfoBarDelegate* translate_delegate =
      delegate->AsTranslateInfoBarDelegate();
  // There can be only 1 translate infobar at any one time.
  return (!!translate_delegate);
}

void TranslateInfoBarDelegate::InfoBarClosed() {
  delete this;
}

// TranslateInfoBarDelegate: public: -------------------------------------------

void TranslateInfoBarDelegate::ModifyOriginalLanguage(
    const std::string& original_language) {
  original_language_ = original_language;
  // TODO(kuan): Send stats to Google Translate that original language has been
  // modified.
}

void TranslateInfoBarDelegate::ModifyTargetLanguage(
    const std::string& target_language) {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::GetAvailableOriginalLanguages(
    std::vector<std::string>* languages) {
  // TODO(kuan): Call backend when it's ready; hardcode a list for now.
  languages->push_back("Arabic");
  languages->push_back("Bengali");
  languages->push_back("Bulgarian");
  languages->push_back("Chinese (Simplified Han)");
  languages->push_back("Chinese (Traditional Han)");
  languages->push_back("Croatian");
  languages->push_back("Czech");
  languages->push_back("Danish");
  languages->push_back("Dutch");
  languages->push_back("English");
  languages->push_back("Estonian");
  languages->push_back("Filipino");
  languages->push_back("Finnish");
  languages->push_back("French");
  languages->push_back("German");
  languages->push_back("Greek");
  languages->push_back("Hebrew");
  languages->push_back("Hindi");
  languages->push_back("Hungarian");
  languages->push_back("Indonesian");
  languages->push_back("Italian");
  languages->push_back("Japanese");
  languages->push_back("Korean");
  languages->push_back("Latvian");
  languages->push_back("Lithuanian");
  languages->push_back("Norwegian");
  languages->push_back("Polish");
  languages->push_back("Portuguese");
  languages->push_back("Romanian");
  languages->push_back("Russian");
  languages->push_back("Serbian");
  languages->push_back("Slovak");
  languages->push_back("Slovenian");
  languages->push_back("Spanish");
  languages->push_back("Swedish");
  languages->push_back("Tamil");
  languages->push_back("Thai");
  languages->push_back("Turkish");
  languages->push_back("Ukrainian");
  languages->push_back("Vietnamese");
}

void TranslateInfoBarDelegate::GetAvailableTargetLanguages(
    std::vector<std::string>* languages) {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::Translate() {
  // TODO(kuan): Call actual Translate method.
/*
  Translate(WideToUTF8(original_language()), WideToUTF8(target_language()));
*/
}

bool TranslateInfoBarDelegate::IsLanguageBlacklisted() {
  NOTREACHED() << "Subclass should override";
  return false;
}

bool TranslateInfoBarDelegate::IsSiteBlacklisted() {
  NOTREACHED() << "Subclass should override";
  return false;
}

bool TranslateInfoBarDelegate::ShouldAlwaysTranslate() {
  NOTREACHED() << "Subclass should override";
  return false;
}

void TranslateInfoBarDelegate::ToggleLanguageBlacklist() {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::ToggleSiteBlacklist() {
  NOTREACHED() << "Subclass should override";
}

void TranslateInfoBarDelegate::ToggleAlwaysTranslate() {
  NOTREACHED() << "Subclass should override";
}

// TranslateInfoBarDelegate: protected: ----------------------------------------

TranslateInfoBarDelegate::TranslateInfoBarDelegate(TabContents* tab_contents,
    PrefService* user_prefs, const std::string& original_language,
    const std::string& target_language)
    : InfoBarDelegate(tab_contents),
      tab_contents_(tab_contents),
      original_language_(original_language),
      target_language_(target_language),
      prefs_(user_prefs) {
}

// BeforeTranslateInfoBarDelegate: public: -------------------------------------

BeforeTranslateInfoBarDelegate::BeforeTranslateInfoBarDelegate(
    TabContents* tab_contents, PrefService* user_prefs, const GURL& url,
    const std::string& original_language, const std::string& target_language)
    : TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
          target_language),
      site_(url.HostNoBrackets()),
      never_translate_language_(false),
      never_translate_site_(false) {
}

bool BeforeTranslateInfoBarDelegate::IsLanguageBlacklisted() {
  never_translate_language_ =
    prefs_.IsLanguageBlacklisted(original_language());
  return never_translate_language_;
}

void BeforeTranslateInfoBarDelegate::ToggleLanguageBlacklist() {
  never_translate_language_ = !never_translate_language_;
  if (never_translate_language_)
    prefs_.BlacklistLanguage(original_language());
  else
    prefs_.RemoveLanguageFromBlacklist(original_language());
}

bool BeforeTranslateInfoBarDelegate::IsSiteBlacklisted() {
  never_translate_site_ = prefs_.IsSiteBlacklisted(site_);
  return never_translate_site_;
}

void BeforeTranslateInfoBarDelegate::ToggleSiteBlacklist() {
  never_translate_site_ = !never_translate_site_;
  if (never_translate_site_)
    prefs_.BlacklistSite(site_);
  else
    prefs_.RemoveSiteFromBlacklist(site_);
}

#if !defined(TOOLKIT_VIEWS)
InfoBar* BeforeTranslateInfoBarDelegate::CreateInfoBar() {
  NOTIMPLEMENTED();
  return NULL;
}
#endif  // !TOOLKIT_VIEWS

// AfterTranslateInfoBarDelegate: public: --------------------------------------

AfterTranslateInfoBarDelegate::AfterTranslateInfoBarDelegate(
    TabContents* tab_contents, PrefService* user_prefs,
    const std::string& original_language, const std::string& target_language)
    : TranslateInfoBarDelegate(tab_contents, user_prefs, original_language,
          target_language),
      always_translate_(false) {
}

void AfterTranslateInfoBarDelegate::GetAvailableTargetLanguages(
    std::vector<std::string>* languages) {
  // TODO(kuan): Call backend when it's ready; hardcode a list for now.
  GetAvailableOriginalLanguages(languages);
}

void AfterTranslateInfoBarDelegate::ModifyTargetLanguage(
    const std::string& target_language) {
  target_language_ = target_language;
}

bool AfterTranslateInfoBarDelegate::ShouldAlwaysTranslate() {
  always_translate_ = prefs_.IsLanguagePairWhitelisted(original_language(),
      target_language());
  return always_translate_;
}

void AfterTranslateInfoBarDelegate::ToggleAlwaysTranslate() {
  always_translate_ = !always_translate_;
  if (always_translate_)
    prefs_.WhitelistLanguagePair(original_language(), target_language());
  else
    prefs_.RemoveLanguagePairFromWhitelist(original_language(),
        target_language());
}

#if !defined(TOOLKIT_VIEWS)
InfoBar* AfterTranslateInfoBarDelegate::CreateInfoBar() {
  NOTIMPLEMENTED();
  return NULL;
}
#endif  // !TOOLKIT_VIEWS
<|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/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  NOTIMPLEMENTED();
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  NOTIMPLEMENTED();
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  NOTIMPLEMENTED();
}
<commit_msg>Convert sandbox NOTIMPLEMENTED()s into a bug.<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/renderer/renderer_main_platform_delegate.h"

#include "base/debug_util.h"

// This is a no op class because we do not have a sandbox on linux.

RendererMainPlatformDelegate::RendererMainPlatformDelegate(
    const MainFunctionParams& parameters)
        : parameters_(parameters) {
}

RendererMainPlatformDelegate::~RendererMainPlatformDelegate() {
}

void RendererMainPlatformDelegate::PlatformInitialize() {
}

void RendererMainPlatformDelegate::PlatformUninitialize() {
}

bool RendererMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
  return true;
}

bool RendererMainPlatformDelegate::EnableSandbox() {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
  return true;
}

void RendererMainPlatformDelegate::RunSandboxTests() {
  // We have no sandbox.
  // http://code.google.com/p/chromium/issues/detail?id=8081
}
<|endoftext|>


<commit_before>#pragma once

#include "ILogger.hpp"
#include "export.h"

#include <vector>
#include <memory>
#include <functional>

namespace samplog
{
	namespace internal
	{
		static const int API_VERSION = 1;
		class IApi
		{
		public:
			virtual void RegisterAmx(AMX *amx) = 0;
			virtual void EraseAmx(AMX *amx) = 0;

			virtual bool GetLastAmxFunctionCall(AMX * const amx,
				AmxFuncCallInfo &destination) = 0;
			virtual bool GetAmxFunctionCallTrace(AMX * const amx,
				std::vector<AmxFuncCallInfo> &dest) = 0;

			virtual samplog::ILogger *CreateLogger(const char *module) = 0;
		};
	}
}

extern "C" DLL_PUBLIC samplog::internal::IApi *samplog_GetApi(int version);
extern "C" DLL_PUBLIC void samplog_DestroyApi(samplog::internal::IApi *api);

#undef DLL_PUBLIC

namespace samplog
{
	using Logger_t = std::unique_ptr<ILogger, std::function<void(ILogger*)>>;

	class Api
	{
	private: // singleton
		enum SingletonAction
		{
			RETURN_LAZY,
			DESTROY
		};

		static Api *SingletonDo(SingletonAction action)
		{
			static Api *api = nullptr;
			switch (action)
			{
			case RETURN_LAZY:
				if (api == nullptr)
					api = new Api;
				break;
			case DESTROY:
				if (api != nullptr)
				{
					delete api;
					api = nullptr;
				}
				break;
			}
			return api;
		}

	public: // singleton
		static Api *Get()
		{
			return SingletonDo(RETURN_LAZY);
		}
		static void Destroy()
		{
			SingletonDo(DESTROY);
		}

	private: // api
		internal::IApi *_api;

	public: // api
		Api() : _api(samplog_GetApi(internal::API_VERSION))
		{ }
		~Api()
		{
			samplog_DestroyApi(_api);
		}
		Api(Api&&) = delete;
		Api& operator=(Api&&) = delete;
		Api(const Api&) = delete;
		Api& operator=(const Api&) = delete;

		inline void RegisterAmx(AMX *amx)
		{
			_api->RegisterAmx(amx);
		}
		inline void EraseAmx(AMX *amx)
		{
			_api->EraseAmx(amx);
		}

		inline bool GetLastAmxFunctionCall(AMX * const amx,
			AmxFuncCallInfo &destination)
		{
			return _api->GetLastAmxFunctionCall(amx, destination);
		}
		inline bool GetAmxFunctionCallTrace(AMX * const amx,
			std::vector<AmxFuncCallInfo> &dest)
		{
			return _api->GetAmxFunctionCallTrace(amx, dest);
		}

		inline Logger_t CreateLogger(const char *module_name)
		{
			return Logger_t(_api->CreateLogger(module_name),
				std::mem_fn(&ILogger::Destroy));
		}
	};
}
<commit_msg>add virtual destructor<commit_after>#pragma once

#include "ILogger.hpp"
#include "export.h"

#include <vector>
#include <memory>
#include <functional>

namespace samplog
{
	namespace internal
	{
		static const int API_VERSION = 1;
		class IApi
		{
		public:
			virtual void RegisterAmx(AMX *amx) = 0;
			virtual void EraseAmx(AMX *amx) = 0;

			virtual bool GetLastAmxFunctionCall(AMX * const amx,
				AmxFuncCallInfo &destination) = 0;
			virtual bool GetAmxFunctionCallTrace(AMX * const amx,
				std::vector<AmxFuncCallInfo> &dest) = 0;

			virtual samplog::ILogger *CreateLogger(const char *module) = 0;

			virtual ~IApi() { }
		};
	}
}

extern "C" DLL_PUBLIC samplog::internal::IApi *samplog_GetApi(int version);
extern "C" DLL_PUBLIC void samplog_DestroyApi(samplog::internal::IApi *api);

#undef DLL_PUBLIC

namespace samplog
{
	using Logger_t = std::unique_ptr<ILogger, std::function<void(ILogger*)>>;

	class Api
	{
	private: // singleton
		enum SingletonAction
		{
			RETURN_LAZY,
			DESTROY
		};

		static Api *SingletonDo(SingletonAction action)
		{
			static Api *api = nullptr;
			switch (action)
			{
			case RETURN_LAZY:
				if (api == nullptr)
					api = new Api;
				break;
			case DESTROY:
				if (api != nullptr)
				{
					delete api;
					api = nullptr;
				}
				break;
			}
			return api;
		}

	public: // singleton
		static Api *Get()
		{
			return SingletonDo(RETURN_LAZY);
		}
		static void Destroy()
		{
			SingletonDo(DESTROY);
		}

	private: // api
		internal::IApi *_api;

	public: // api
		Api() : _api(samplog_GetApi(internal::API_VERSION))
		{ }
		~Api()
		{
			samplog_DestroyApi(_api);
		}
		Api(Api&&) = delete;
		Api& operator=(Api&&) = delete;
		Api(const Api&) = delete;
		Api& operator=(const Api&) = delete;

		inline void RegisterAmx(AMX *amx)
		{
			_api->RegisterAmx(amx);
		}
		inline void EraseAmx(AMX *amx)
		{
			_api->EraseAmx(amx);
		}

		inline bool GetLastAmxFunctionCall(AMX * const amx,
			AmxFuncCallInfo &destination)
		{
			return _api->GetLastAmxFunctionCall(amx, destination);
		}
		inline bool GetAmxFunctionCallTrace(AMX * const amx,
			std::vector<AmxFuncCallInfo> &dest)
		{
			return _api->GetAmxFunctionCallTrace(amx, dest);
		}

		inline Logger_t CreateLogger(const char *module_name)
		{
			return Logger_t(_api->CreateLogger(module_name),
				std::mem_fn(&ILogger::Destroy));
		}
	};
}
<|endoftext|>


<commit_before>#include<bits/stdc++.h>
using namespace std;

int main()

{
int t,n;
scanf("%d",&t);
while(t--)
{
	char a[100005];
scanf("%s",&a);
int n=strlen(a);
int sum=0;
for(int i=0;i<n;i++)
{
sum+=a[i]-'0';

}

if(sum<9&&n>1)
{
	printf("%d\n",(9-(sum%9)));
}

else
{

printf("%d\n",min((9-(sum%9)),sum%9));
}
}

return 0;
}
<commit_msg>Delete DIVNINE.cpp<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCommunicator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCommunicator.h"

#include "vtkCharArray.h"
#include "vtkDataSetReader.h"
#include "vtkDataSetWriter.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageClip.h"
#include "vtkIntArray.h"
#include "vtkStructuredPoints.h"
#include "vtkStructuredPointsReader.h"
#include "vtkStructuredPointsWriter.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedLongArray.h"

vtkCxxRevisionMacro(vtkCommunicator, "1.25");

template <class T>
int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self)
{

  self->Send(data, length, handle, tag);

  return 1;
}

vtkCommunicator::vtkCommunicator()
{
  this->MarshalString = 0;
  this->MarshalStringLength = 0;
  this->MarshalDataLength = 0;
}

vtkCommunicator::~vtkCommunicator()
{
  this->DeleteAndSetMarshalString(0, 0);
}

int vtkCommunicator::UseCopy = 0;
void vtkCommunicator::SetUseCopy(int useCopy)
{
  vtkCommunicator::UseCopy = useCopy;
}

void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Marshal string: ";
  if ( this->MarshalString )
    {
    os << this->MarshalString << endl;
    }
  else
    {
    os << "(None)" << endl;
    }
  os << indent << "Marshal string length: " << this->MarshalStringLength
     << endl;
  os << indent << "Marshal data length: " << this->MarshalDataLength
     << endl;
}

//----------------------------------------------------------------------------
// Internal method.  Assumes responsibility for deleting the string
void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength)
{
  // delete any previous string
  if (this->MarshalString)
    {
    delete [] this->MarshalString;
    this->MarshalString = 0;
    this->MarshalStringLength = 0;
    this->MarshalDataLength = 0;
    }

  this->MarshalString = str;
  this->MarshalStringLength = strLength;
}

// Need to add better error checking
int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle,
                          int tag)
{

  if (data == NULL)
    {
    this->MarshalDataLength = 0;
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    return 1;
    }
  if (this->WriteObject(data))
    {
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    // then send the string.

    this->Send( this->MarshalString, this->MarshalDataLength,
                remoteHandle, tag);

    return 1;
    }

  // could not marshal data
  return 0;
}

int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag)
{

  int type = -1;
  if (data == NULL)
    {
      this->MarshalDataLength = 0;
      this->Send( &type, 1, remoteHandle, tag);
      return 1;
    }

  // send array type
  type = data->GetDataType();
  this->Send( &type, 1, remoteHandle, tag);

  // send array size
  vtkIdType size = data->GetSize();
  this->Send( &size, 1, remoteHandle, tag);

  // send number of components in array
  int numComponents = data->GetNumberOfComponents();
  this->Send( &numComponents, 1, remoteHandle, tag);

  const char* name = data->GetName();
  int len = 0;
  if (name)
    {
    len = static_cast<int>(strlen(name)) + 1;
    }

  // send length of name
  this->Send( &len, 1, remoteHandle, tag);

  if (len > 0)
    {
    // send name
    this->Send( const_cast<char*>(name), len, remoteHandle, tag);
    }

  // now send the raw array
  switch (type)
    {

    case VTK_CHAR:
      return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_CHAR:
      return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_INT:
      return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_LONG:
      return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_FLOAT:
      return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_DOUBLE:
      return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_ID_TYPE:
      return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

}

int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle,
                             int tag)
{
  int dataLength;

  // First receive the data length.
  if (!this->Receive( &dataLength, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (dataLength < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (dataLength == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // if we cannot reuse the string, allocate a new one.
  if (dataLength > this->MarshalStringLength)
    {
    char *str = new char[dataLength + 10]; // maybe a little extra?
    this->DeleteAndSetMarshalString(str, dataLength + 10);
    }

  // Receive the string
  this->Receive(this->MarshalString, dataLength,
                remoteHandle, tag);
  this->MarshalDataLength = dataLength;

  this->ReadObject(data);

  // we should really look at status to determine success
  return 1;
}

int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle,
                             int tag)
{
  vtkIdType size;
  int type;
  int numComponents;
  int nameLength;

  char *c = 0;
  unsigned char *uc = 0;
  int *i = 0;
  unsigned long *ul = 0;
  float *f = 0;
  double *d = 0;
  vtkIdType *idt = 0;

  // First receive the data type.
  if (!this->Receive( &type, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (type == -1)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Next receive the data length.
  if (!this->Receive( &size, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  // Next receive the number of components.
  this->Receive( &numComponents, 1, remoteHandle, tag);

  // Next receive the length of the name.
  this->Receive( &nameLength, 1, remoteHandle, tag);

  if ( nameLength > 0 )
    {
    char *str = new char[nameLength];
    this->DeleteAndSetMarshalString(str, nameLength);

    // Receive the name
    this->Receive(this->MarshalString, nameLength, remoteHandle, tag);
    this->MarshalDataLength = nameLength;
    }

  if (size < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (size == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Receive the raw data array
  switch (type)
    {

    case VTK_CHAR:
      c = new char[size];
      this->Receive(c, size, remoteHandle, tag);
      static_cast<vtkCharArray*>(data)->SetArray(c, size, 0);
      break;

    case VTK_UNSIGNED_CHAR:
      uc = new unsigned char[size];
      this->Receive(uc, size, remoteHandle, tag);
      static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0);
      break;

    case VTK_INT:
      i = new int[size];
      this->Receive(i, size, remoteHandle, tag);
      static_cast<vtkIntArray*>(data)->SetArray(i, size, 0);
      break;

    case VTK_UNSIGNED_LONG:
      ul = new unsigned long[size];
      this->Receive(ul, size, remoteHandle, tag);
      static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0);
      break;

    case VTK_FLOAT:
      f = new float[size];
      this->Receive(f, size, remoteHandle, tag);
      static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0);
      break;

    case VTK_DOUBLE:

      d = new double[size];
      this->Receive(d, size, remoteHandle, tag);
      static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0);
      break;

    case VTK_ID_TYPE:
      idt = new vtkIdType[size];
      this->Receive(idt, size, remoteHandle, tag);
      static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0);
      break;

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

  if (nameLength > 0)
    {
    data->SetName(this->MarshalString);
    }
  else
    {
    data->SetName(0);
    }
  data->SetNumberOfComponents(numComponents);

  return 1;

}

int vtkCommunicator::WriteObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->WriteDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->WriteImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());
  return 0;
}

int vtkCommunicator::ReadObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->ReadDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->ReadImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());

  return 1;
}

int vtkCommunicator::WriteImageData(vtkImageData *data)
{
  vtkImageClip *clip;
  vtkStructuredPointsWriter *writer;
  int size;

  // keep Update from propagating
  vtkImageData *tmp = vtkImageData::New();
  tmp->ShallowCopy(data);
  tmp->SetUpdateExtent(data->GetUpdateExtent());

  clip = vtkImageClip::New();
  clip->SetInput(tmp);
  clip->SetOutputWholeExtent(data->GetExtent());
  writer = vtkStructuredPointsWriter::New();
  writer->SetFileTypeToBinary();
  writer->WriteToOutputStringOn();
  writer->SetInput(clip->GetOutput());
  writer->Write();
  size = writer->GetOutputStringLength();

  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  clip->Delete();
  writer->Delete();
  tmp->Delete();

  return 1;
}

int vtkCommunicator::ReadImageData(vtkImageData *object)
{
  vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->GetOutput()->Update();

  object->ShallowCopy(reader->GetOutput());
  object->SetUpdateExtent(reader->GetOutput()->GetUpdateExtent());

  reader->Delete();

  return 1;
}

int vtkCommunicator::WriteDataSet(vtkDataSet *data)
{
  vtkDataSet *copy;
  unsigned long size;
  vtkDataSetWriter *writer = vtkDataSetWriter::New();

  copy = data->NewInstance();
  copy->ShallowCopy(data);

  // There is a problem with binary files with no data.
  if (copy->GetNumberOfCells() + copy->GetNumberOfPoints() > 0)
    {
    writer->SetFileTypeToBinary();
    }
  writer->WriteToOutputStringOn();
  writer->SetInput(copy);

  writer->Write();
  size = writer->GetOutputStringLength();
  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  writer->Delete();
  copy->Delete();

  return 1;
}

int vtkCommunicator::ReadDataSet(vtkDataSet *object)
{
  vtkDataSet *output;
  vtkDataSetReader *reader = vtkDataSetReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->Update();
  object->ShallowCopy(reader->GetOutput());

  reader->Delete();

  return 1;
}
<commit_msg>COMP: Fixed warning<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkCommunicator.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCommunicator.h"

#include "vtkCharArray.h"
#include "vtkDataSetReader.h"
#include "vtkDataSetWriter.h"
#include "vtkDoubleArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkImageClip.h"
#include "vtkIntArray.h"
#include "vtkStructuredPoints.h"
#include "vtkStructuredPointsReader.h"
#include "vtkStructuredPointsWriter.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnsignedLongArray.h"

vtkCxxRevisionMacro(vtkCommunicator, "1.26");

template <class T>
int SendDataArray(T* data, int length, int handle, int tag, vtkCommunicator *self)
{

  self->Send(data, length, handle, tag);

  return 1;
}

vtkCommunicator::vtkCommunicator()
{
  this->MarshalString = 0;
  this->MarshalStringLength = 0;
  this->MarshalDataLength = 0;
}

vtkCommunicator::~vtkCommunicator()
{
  this->DeleteAndSetMarshalString(0, 0);
}

int vtkCommunicator::UseCopy = 0;
void vtkCommunicator::SetUseCopy(int useCopy)
{
  vtkCommunicator::UseCopy = useCopy;
}

void vtkCommunicator::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Marshal string: ";
  if ( this->MarshalString )
    {
    os << this->MarshalString << endl;
    }
  else
    {
    os << "(None)" << endl;
    }
  os << indent << "Marshal string length: " << this->MarshalStringLength
     << endl;
  os << indent << "Marshal data length: " << this->MarshalDataLength
     << endl;
}

//----------------------------------------------------------------------------
// Internal method.  Assumes responsibility for deleting the string
void vtkCommunicator::DeleteAndSetMarshalString(char *str, int strLength)
{
  // delete any previous string
  if (this->MarshalString)
    {
    delete [] this->MarshalString;
    this->MarshalString = 0;
    this->MarshalStringLength = 0;
    this->MarshalDataLength = 0;
    }

  this->MarshalString = str;
  this->MarshalStringLength = strLength;
}

// Need to add better error checking
int vtkCommunicator::Send(vtkDataObject* data, int remoteHandle,
                          int tag)
{

  if (data == NULL)
    {
    this->MarshalDataLength = 0;
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    return 1;
    }
  if (this->WriteObject(data))
    {
    this->Send( &this->MarshalDataLength, 1,
                remoteHandle, tag);
    // then send the string.

    this->Send( this->MarshalString, this->MarshalDataLength,
                remoteHandle, tag);

    return 1;
    }

  // could not marshal data
  return 0;
}

int vtkCommunicator::Send(vtkDataArray* data, int remoteHandle, int tag)
{

  int type = -1;
  if (data == NULL)
    {
      this->MarshalDataLength = 0;
      this->Send( &type, 1, remoteHandle, tag);
      return 1;
    }

  // send array type
  type = data->GetDataType();
  this->Send( &type, 1, remoteHandle, tag);

  // send array size
  vtkIdType size = data->GetSize();
  this->Send( &size, 1, remoteHandle, tag);

  // send number of components in array
  int numComponents = data->GetNumberOfComponents();
  this->Send( &numComponents, 1, remoteHandle, tag);

  const char* name = data->GetName();
  int len = 0;
  if (name)
    {
    len = static_cast<int>(strlen(name)) + 1;
    }

  // send length of name
  this->Send( &len, 1, remoteHandle, tag);

  if (len > 0)
    {
    // send name
    this->Send( const_cast<char*>(name), len, remoteHandle, tag);
    }

  // now send the raw array
  switch (type)
    {

    case VTK_CHAR:
      return SendDataArray(static_cast<char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_CHAR:
      return SendDataArray(static_cast<unsigned char*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_INT:
      return SendDataArray(static_cast<int*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_UNSIGNED_LONG:
      return SendDataArray(static_cast<unsigned long*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_FLOAT:
      return SendDataArray(static_cast<float*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_DOUBLE:
      return SendDataArray(static_cast<double*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    case VTK_ID_TYPE:
      return SendDataArray(static_cast<vtkIdType*>(data->GetVoidPointer(0)),
                          size, remoteHandle, tag, this);

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

}

int vtkCommunicator::Receive(vtkDataObject* data, int remoteHandle,
                             int tag)
{
  int dataLength;

  // First receive the data length.
  if (!this->Receive( &dataLength, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (dataLength < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (dataLength == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // if we cannot reuse the string, allocate a new one.
  if (dataLength > this->MarshalStringLength)
    {
    char *str = new char[dataLength + 10]; // maybe a little extra?
    this->DeleteAndSetMarshalString(str, dataLength + 10);
    }

  // Receive the string
  this->Receive(this->MarshalString, dataLength,
                remoteHandle, tag);
  this->MarshalDataLength = dataLength;

  this->ReadObject(data);

  // we should really look at status to determine success
  return 1;
}

int vtkCommunicator::Receive(vtkDataArray* data, int remoteHandle,
                             int tag)
{
  vtkIdType size;
  int type;
  int numComponents;
  int nameLength;

  char *c = 0;
  unsigned char *uc = 0;
  int *i = 0;
  unsigned long *ul = 0;
  float *f = 0;
  double *d = 0;
  vtkIdType *idt = 0;

  // First receive the data type.
  if (!this->Receive( &type, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  if (type == -1)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Next receive the data length.
  if (!this->Receive( &size, 1, remoteHandle, tag))
    {
    vtkErrorMacro("Could not receive data!");
    return 0;
    }

  // Next receive the number of components.
  this->Receive( &numComponents, 1, remoteHandle, tag);

  // Next receive the length of the name.
  this->Receive( &nameLength, 1, remoteHandle, tag);

  if ( nameLength > 0 )
    {
    char *str = new char[nameLength];
    this->DeleteAndSetMarshalString(str, nameLength);

    // Receive the name
    this->Receive(this->MarshalString, nameLength, remoteHandle, tag);
    this->MarshalDataLength = nameLength;
    }

  if (size < 0)
    {
    vtkErrorMacro("Bad data length");
    return 0;
    }

  if (size == 0)
    { // This indicates a NULL object was sent. Do nothing.
    return 1;
    }

  // Receive the raw data array
  switch (type)
    {

    case VTK_CHAR:
      c = new char[size];
      this->Receive(c, size, remoteHandle, tag);
      static_cast<vtkCharArray*>(data)->SetArray(c, size, 0);
      break;

    case VTK_UNSIGNED_CHAR:
      uc = new unsigned char[size];
      this->Receive(uc, size, remoteHandle, tag);
      static_cast<vtkUnsignedCharArray*>(data)->SetArray(uc, size, 0);
      break;

    case VTK_INT:
      i = new int[size];
      this->Receive(i, size, remoteHandle, tag);
      static_cast<vtkIntArray*>(data)->SetArray(i, size, 0);
      break;

    case VTK_UNSIGNED_LONG:
      ul = new unsigned long[size];
      this->Receive(ul, size, remoteHandle, tag);
      static_cast<vtkUnsignedLongArray*>(data)->SetArray(ul, size, 0);
      break;

    case VTK_FLOAT:
      f = new float[size];
      this->Receive(f, size, remoteHandle, tag);
      static_cast<vtkFloatArray*>(data)->SetArray(f, size, 0);
      break;

    case VTK_DOUBLE:

      d = new double[size];
      this->Receive(d, size, remoteHandle, tag);
      static_cast<vtkDoubleArray*>(data)->SetArray(d, size, 0);
      break;

    case VTK_ID_TYPE:
      idt = new vtkIdType[size];
      this->Receive(idt, size, remoteHandle, tag);
      static_cast<vtkIdTypeArray*>(data)->SetArray(idt, size, 0);
      break;

    default:
      vtkErrorMacro(<<"Unsupported data type!");
      return 0; // could not marshal data

    }

  if (nameLength > 0)
    {
    data->SetName(this->MarshalString);
    }
  else
    {
    data->SetName(0);
    }
  data->SetNumberOfComponents(numComponents);

  return 1;

}

int vtkCommunicator::WriteObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->WriteDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->WriteImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());
  return 0;
}

int vtkCommunicator::ReadObject(vtkDataObject *data)
{
  if (strcmp(data->GetClassName(), "vtkPolyData") == 0          ||
      strcmp(data->GetClassName(), "vtkUnstructuredGrid") == 0  ||
      strcmp(data->GetClassName(), "vtkStructuredGrid") == 0    ||
      strcmp(data->GetClassName(), "vtkRectilinearGrid") == 0   ||
      strcmp(data->GetClassName(), "vtkStructuredPoints") == 0)
    {
    return this->ReadDataSet((vtkDataSet*)data);
    }
  if (strcmp(data->GetClassName(), "vtkImageData") == 0)
    {
    return this->ReadImageData((vtkImageData*)data);
    }

  vtkErrorMacro("Cannot marshal object of type "
                << data->GetClassName());

  return 1;
}

int vtkCommunicator::WriteImageData(vtkImageData *data)
{
  vtkImageClip *clip;
  vtkStructuredPointsWriter *writer;
  int size;

  // keep Update from propagating
  vtkImageData *tmp = vtkImageData::New();
  tmp->ShallowCopy(data);
  tmp->SetUpdateExtent(data->GetUpdateExtent());

  clip = vtkImageClip::New();
  clip->SetInput(tmp);
  clip->SetOutputWholeExtent(data->GetExtent());
  writer = vtkStructuredPointsWriter::New();
  writer->SetFileTypeToBinary();
  writer->WriteToOutputStringOn();
  writer->SetInput(clip->GetOutput());
  writer->Write();
  size = writer->GetOutputStringLength();

  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  clip->Delete();
  writer->Delete();
  tmp->Delete();

  return 1;
}

int vtkCommunicator::ReadImageData(vtkImageData *object)
{
  vtkStructuredPointsReader *reader = vtkStructuredPointsReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->GetOutput()->Update();

  object->ShallowCopy(reader->GetOutput());
  object->SetUpdateExtent(reader->GetOutput()->GetUpdateExtent());

  reader->Delete();

  return 1;
}

int vtkCommunicator::WriteDataSet(vtkDataSet *data)
{
  vtkDataSet *copy;
  unsigned long size;
  vtkDataSetWriter *writer = vtkDataSetWriter::New();

  copy = data->NewInstance();
  copy->ShallowCopy(data);

  // There is a problem with binary files with no data.
  if (copy->GetNumberOfCells() + copy->GetNumberOfPoints() > 0)
    {
    writer->SetFileTypeToBinary();
    }
  writer->WriteToOutputStringOn();
  writer->SetInput(copy);

  writer->Write();
  size = writer->GetOutputStringLength();
  this->DeleteAndSetMarshalString(writer->RegisterAndGetOutputString(), size);
  this->MarshalDataLength = size;
  writer->Delete();
  copy->Delete();

  return 1;
}

int vtkCommunicator::ReadDataSet(vtkDataSet *object)
{
  vtkDataSetReader *reader = vtkDataSetReader::New();

  if (this->MarshalString == NULL || this->MarshalStringLength <= 0)
    {
    return 0;
    }

  reader->ReadFromInputStringOn();

  vtkCharArray* mystring = vtkCharArray::New();
  // mystring should not delete the string when it's done,
  // that's our job.
  mystring->SetArray(this->MarshalString, this->MarshalDataLength, 1);
  reader->SetInputArray(mystring);
  mystring->Delete();

  reader->Update();
  object->ShallowCopy(reader->GetOutput());

  reader->Delete();

  return 1;
}
<|endoftext|>