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

#include "chrome/common/chrome_switches.h"

#include "base/base_switches.h"

namespace switches {

// Can't find the switch you are looking for? try looking in
// base/base_switches.cc instead.

// Suppresses hang monitor dialogs in renderer processes.
const wchar_t kDisableHangMonitor[]            = L"disable-hang-monitor";

// Completely disables UMA metrics system.
const wchar_t kDisableMetrics[]                = L"disable-metrics";

// Disables only the sending of metrics reports.  In contrast to
// kDisableMetrics, this executes all the code that a normal client would use
// for reporting, except the report is dropped rather than sent to the server.
// This is useful for finding issues in the metrics code during UI and
// performance tests.
const wchar_t kDisableMetricsReporting[]       = L"disable-metrics-reporting";

// Causes the browser process to throw an assertion on startup.
const wchar_t kBrowserAssertTest[]             = L"assert-test";

// Causes the renderer process to throw an assertion on launch.
const wchar_t kRendererAssertTest[]            = L"renderer-assert-test";

// Causes the browser process to crash on startup.
const wchar_t kBrowserCrashTest[]              = L"crash-test";

// Causes the renderer process to crash on launch.
const wchar_t kRendererCrashTest[]             = L"renderer-crash-test";

// Causes the renderer process to display a dialog on launch.
const wchar_t kRendererStartupDialog[]         = L"renderer-startup-dialog";

// Causes the plugin process to display a dialog on launch.
const wchar_t kPluginStartupDialog[]           = L"plugin-startup-dialog";

// Causes the test shell process to display a dialog on launch.
const wchar_t kTestShellStartupDialog[]        = L"testshell-startup-dialog";

// Specifies a command that should be used to launch the plugin process.  Useful
// for running the plugin process through purify or quantify.  Ex:
//   --plugin-launcher="path\to\purify /Run=yes"
const wchar_t kPluginLauncher[]                = L"plugin-launcher";

// The value of this switch tells the child process which
// IPC channel the browser expects to use to communicate with it.
const wchar_t kProcessChannelID[]              = L"channel";

// The value of this switch tells the app to listen for and broadcast
// testing-related messages on IPC channel with the given ID.
const wchar_t kTestingChannelID[]              = L"testing-channel";

// The value of this switch specifies which page will be displayed
// in newly-opened tabs.  We need this for testing purposes so
// that the UI tests don't depend on what comes up for http://google.com.
const wchar_t kHomePage[]                      = L"homepage";

// When this switch is present, the browser will throw up a dialog box
// asking the user to start a renderer process independently rather
// than launching the renderer itself.  (This is useful for debugging.)
const wchar_t kBrowserStartRenderersManually[] = L"start-renderers-manually";

// Causes the process to run as renderer instead of as browser.
const wchar_t kRendererProcess[]               = L"renderer";

// Path to the exe to run for the renderer subprocess
const wchar_t kRendererPath[]                  = L"renderer-path";

// Causes the process to run as plugin host
const wchar_t kPluginProcess[]                 = L"plugin";

// Runs the renderer and plugins in the same process as the browser
const wchar_t kSingleProcess[]                 = L"single-process";

// Runs each set of script-connected tabs (i.e., a BrowsingInstance) in its own
// renderer process.  We default to using a renderer process for each
// site instance (i.e., group of pages from the same registered domain with
// script connections to each other).
const wchar_t kProcessPerTab[] = L"process-per-tab";

// Runs a single process for each site (i.e., group of pages from the same
// registered domain) the user visits.  We default to using a renderer process
// for each site instance (i.e., group of pages from the same registered
// domain with script connections to each other).
const wchar_t kProcessPerSite[] = L"process-per-site";

// Runs plugins inside the renderer process
const wchar_t kInProcessPlugins[]              = L"in-process-plugins";

// Runs the renderer outside the sandbox.
const wchar_t kNoSandbox[]                     = L"no-sandbox";

// Runs the plugin processes inside the sandbox.
const wchar_t kSafePlugins[]                   = L"safe-plugins";

// Excludes these plugins from the plugin sandbox.
// This is a comma separated list of plugin dlls name and activex clsid.
const wchar_t kTrustedPlugins[]                = L"trusted-plugins";

// Runs the security test for the sandbox.
const wchar_t kTestSandbox[]                   = L"test-sandbox";

// Specifies the user data directory, which is where the browser will look
// for all of its state.
const wchar_t kUserDataDir[]                   = L"user-data-dir";

// Specifies that the associated value should be launched in "application" mode.
const wchar_t kApp[]                           = L"app";

// Specifies the file that should be uploaded to the provided application. This
// switch is expected to be used with --app option.
const wchar_t kAppUploadFile[]                 = L"upload-file";

// Specifies if the dom_automation_controller_ needs to be bound in the
// renderer. This binding happens on per-frame basis and hence can potentially
// be a performance bottleneck. One should only enable it when automating
// dom based tests.
const wchar_t kDomAutomationController[]       = L"dom-automation";

// Tells the plugin process the path of the plugin to load
const wchar_t kPluginPath[]                    = L"plugin-path";

// Specifies the flags passed to JS engine
const wchar_t kJavaScriptFlags[]               = L"js-flags";

// The GeoID we should use.  This is normally obtained from the operating system
// during first run and cached in the preferences afterwards.  This is a numeric
// value; see http://msdn.microsoft.com/en-us/library/ms776390.aspx .
const wchar_t kGeoID[]                         = L"geoid";

// The language file that we want to try to open.  Of the form
// language[-country] where language is the 2 letter code from ISO-639.
const wchar_t kLang[]                          = L"lang";

// Will add kDebugOnStart to every child processes. If a value is passed, it
// will be used as a filter to determine if the child process should have the
// kDebugOnStart flag passed on or not.
const wchar_t kDebugChildren[]                 = L"debug-children";

// Will add kWaitForDebugger to every child processes. If a value is passed, it
// will be used as a filter to determine if the child process should have the
// kWaitForDebugger flag passed on or not.
const wchar_t kWaitForDebuggerChildren[]       = L"wait-for-debugger-children";

// Will filter log messages to show only the messages that are prefixed
// with the specified value
const wchar_t kLogFilterPrefix[]               = L"log-filter-prefix";

// Force logging to be enabled.  Logging is disabled by default in release
// builds.
const wchar_t kEnableLogging[]                 = L"enable-logging";

// Force logging to be disabled.  Logging is enabled by default in debug
// builds.
const wchar_t kDisableLogging[]                = L"disable-logging";

// Sets the minimum log level. Valid values are from 0 to 3:
// INFO = 0, WARNING = 1, LOG_ERROR = 2, LOG_FATAL = 3.
const wchar_t kLoggingLevel[]                  = L"log-level";

// Dump any accumualted histograms to the log when browser terminates (requires
// logging to be enabled to really do anything).  Used by developers and test
// scripts.
const wchar_t kDumpHistogramsOnExit[]          = L"dump-histograms-on-exit";

// enable remote debug / automation shell on the specified port
const wchar_t kRemoteShellPort[]               = L"remote-shell-port";

// Runs un-installation steps that were done by chrome first-run.
const wchar_t kUninstall[]                     = L"uninstall";

// Number of entries to show in the omnibox popup.
const wchar_t kOmniBoxPopupCount[]             = L"omnibox-popup-count";

// The value of this switch tells the app to listen for and broadcast
// automation-related messages on IPC channel with the given ID.
const wchar_t kAutomationClientChannelID[]        = L"automation-channel";

// Indicates the last session should be restored on startup. This overrides
// the preferences value and is primarily intended for testing.
const wchar_t kRestoreLastSession[] = L"restore-last-session";

// Chrome supports a playback and record mode.  Record mode saves *everything*
// to the cache.  Playback mode reads data exclusively from the cache.  This
// allows us to record a session into the cache and then replay it at will.
const wchar_t kRecordMode[] = L"record-mode";
const wchar_t kPlaybackMode[] = L"playback-mode";

// Don't record/playback events when using record & playback.
const wchar_t kNoEvents[] = L"no-events";

// Make Windows happy by allowing it to show "Enable access to this program"
// checkbox in Add/Remove Programs->Set Program Access and Defaults. This
// only shows an error box because the only way to hide Chrome is by
// uninstalling it.
const wchar_t kHideIcons[] = L"hide-icons";

const wchar_t kShowIcons[] = L"show-icons";

// Make Chrome default browser
const wchar_t kMakeDefaultBrowser[] = L"make-default-browser";

// Use a specified proxy server, overrides system settings. This switch only
// affects HTTP and HTTPS requests.
const wchar_t kProxyServer[] = L"proxy-server";

// Chrome will support prefetching of DNS information.  Until this becomes
// the default, we'll provide a command line switch.
extern const wchar_t kDnsLogDetails[] = L"dns-log-details";
extern const wchar_t kDnsPrefetchDisable[] = L"dns-prefetch-disable";

// Enables support to debug printing subsystem.
const wchar_t kDebugPrint[] = L"debug-print";

// Allow initialization of all activex controls. This is only to help website
// developers test their controls to see if they are compatible in Chrome.
// Note there's a duplicate value in activex_shared.cc (to avoid
// dependency on chrome module). Please change both locations at the same time.
const wchar_t kAllowAllActiveX[] = L"allow-all-activex";

// Browser flag to disable the web inspector for all renderers.
const wchar_t kDisableDevTools[] = L"disable-dev-tools";

// Enable web inspector for all windows, even if they're part of the browser.
// Allows us to use our dev tools to debug browser windows itself.
const wchar_t kAlwaysEnableDevTools[] = L"always-enable-dev-tools";

// Used to set the value of SessionRestore::num_tabs_to_load_. See
// session_restore.h for details.
const wchar_t kTabCountToLoadOnSessionRestore[] =
    L"tab-count-to-load-on-session-restore";

// Enable dynamic loading of the Memory Profiler DLL, which will trace
// all memory allocations during the run.
const wchar_t kMemoryProfiling[] = L"memory-profile";

// Configure Chrome's memory model.
// Does chrome really need multiple memory models?  No.  But we get a lot
// of concerns from individuals about how the changes work on *their*
// system, and we need to be able to experiment with a few choices.
const wchar_t kMemoryModel[] = L"memory-model";

// By default, cookies are not allowed on file://. They are needed in for
// testing, for example page cycler and layout tests.  See bug 1157243.
const wchar_t kEnableFileCookies[] = L"enable-file-cookies";

// Start the browser maximized, regardless of any previous settings.
// TODO(pjohnson): Remove this once bug 1137420 is fixed.  We are using this
// as a workaround for not being able to use moveTo and resizeTo on a
// top-level window.
const wchar_t kStartMaximized[] = L"start-maximized";

// Spawn threads to watch for excessive delays in specified message loops.
// User should set breakpoints on Alarm() to examine problematic thread.
// Usage:   -enable-watchdog=[ui][io]
// Order of the listed sub-arguments does not matter.
const wchar_t kEnableWatchdog[] = L"enable-watchdog";

// Display the First Run experience when the browser is started, regardless of
// whether or not it's actually the first run.
const wchar_t kFirstRun[] = L"first-run";

// Enable histograming of tasks served by MessageLoop. See about:histograms/Loop
// for results, which show frequency of messages on each thread, including APC
// count, object signalling count, etc.
const wchar_t kMessageLoopHistogrammer[] = L"message-loop-histogrammer";

// Perform importing from another browser. The value associated with this
// setting encodes the target browser and what items to import.
const wchar_t kImport[] = L"import";

// Change the DCHECKS to dump memory and continue instead of crashing.
// This is valid only in Release mode when --enable-dcheck is specified.
const wchar_t kSilentDumpOnDCHECK[] = L"silent-dump-on-dcheck";

// Normally when the user attempts to navigate to a page that was the result of
// a post we prompt to make sure they want to. This switch may be used to
// disable that check. This switch is used during automated testing.
const wchar_t kDisablePromptOnRepost[] = L"disable-prompt-on-repost";

// Disable pop-up blocking.
const wchar_t kDisablePopupBlocking[] = L"disable-popup-blocking";

// Don't execute JavaScript (browser JS like the new tab page still runs).
const wchar_t kDisableJavaScript[] = L"disable-javascript";

// Prevent Java from running.
const wchar_t kDisableJava[] = L"disable-java";

// Prevent plugins from running.
const wchar_t kDisablePlugins[] = L"disable-plugins";

// Prevent images from loading.
const wchar_t kDisableImages[] = L"disable-images";

// Use the low fragmentation heap for the CRT.
const wchar_t kUseLowFragHeapCrt[] = L"use-lf-heap";

#ifndef NDEBUG
// Debug only switch to specify which gears plugin dll to load.
const wchar_t kGearsPluginPathOverride[] = L"gears-plugin-path";
#endif

// Switch to load Gears in the renderer process.
const wchar_t kGearsInRenderer[] = L"gears-in-renderer";

// Enable new HTTP stack.
const wchar_t kUseNewHttp[] = L"new-http";

// Allow loading of the javascript debugger UI from the filesystem.
const wchar_t kJavaScriptDebuggerPath[] = L"javascript-debugger-path";

const wchar_t kEnableP13n[] = L"enable-p13n";

}  // namespace switches

<commit_msg>Remove the TODO to remove --start-maximized.  It seems this switch is actually useful for users, so I see no problem in keeping it. Review URL: http://codereview.chromium.org/3038<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/chrome_switches.h"

#include "base/base_switches.h"

namespace switches {

// Can't find the switch you are looking for? try looking in
// base/base_switches.cc instead.

// Suppresses hang monitor dialogs in renderer processes.
const wchar_t kDisableHangMonitor[]            = L"disable-hang-monitor";

// Completely disables UMA metrics system.
const wchar_t kDisableMetrics[]                = L"disable-metrics";

// Disables only the sending of metrics reports.  In contrast to
// kDisableMetrics, this executes all the code that a normal client would use
// for reporting, except the report is dropped rather than sent to the server.
// This is useful for finding issues in the metrics code during UI and
// performance tests.
const wchar_t kDisableMetricsReporting[]       = L"disable-metrics-reporting";

// Causes the browser process to throw an assertion on startup.
const wchar_t kBrowserAssertTest[]             = L"assert-test";

// Causes the renderer process to throw an assertion on launch.
const wchar_t kRendererAssertTest[]            = L"renderer-assert-test";

// Causes the browser process to crash on startup.
const wchar_t kBrowserCrashTest[]              = L"crash-test";

// Causes the renderer process to crash on launch.
const wchar_t kRendererCrashTest[]             = L"renderer-crash-test";

// Causes the renderer process to display a dialog on launch.
const wchar_t kRendererStartupDialog[]         = L"renderer-startup-dialog";

// Causes the plugin process to display a dialog on launch.
const wchar_t kPluginStartupDialog[]           = L"plugin-startup-dialog";

// Causes the test shell process to display a dialog on launch.
const wchar_t kTestShellStartupDialog[]        = L"testshell-startup-dialog";

// Specifies a command that should be used to launch the plugin process.  Useful
// for running the plugin process through purify or quantify.  Ex:
//   --plugin-launcher="path\to\purify /Run=yes"
const wchar_t kPluginLauncher[]                = L"plugin-launcher";

// The value of this switch tells the child process which
// IPC channel the browser expects to use to communicate with it.
const wchar_t kProcessChannelID[]              = L"channel";

// The value of this switch tells the app to listen for and broadcast
// testing-related messages on IPC channel with the given ID.
const wchar_t kTestingChannelID[]              = L"testing-channel";

// The value of this switch specifies which page will be displayed
// in newly-opened tabs.  We need this for testing purposes so
// that the UI tests don't depend on what comes up for http://google.com.
const wchar_t kHomePage[]                      = L"homepage";

// When this switch is present, the browser will throw up a dialog box
// asking the user to start a renderer process independently rather
// than launching the renderer itself.  (This is useful for debugging.)
const wchar_t kBrowserStartRenderersManually[] = L"start-renderers-manually";

// Causes the process to run as renderer instead of as browser.
const wchar_t kRendererProcess[]               = L"renderer";

// Path to the exe to run for the renderer subprocess
const wchar_t kRendererPath[]                  = L"renderer-path";

// Causes the process to run as plugin host
const wchar_t kPluginProcess[]                 = L"plugin";

// Runs the renderer and plugins in the same process as the browser
const wchar_t kSingleProcess[]                 = L"single-process";

// Runs each set of script-connected tabs (i.e., a BrowsingInstance) in its own
// renderer process.  We default to using a renderer process for each
// site instance (i.e., group of pages from the same registered domain with
// script connections to each other).
const wchar_t kProcessPerTab[] = L"process-per-tab";

// Runs a single process for each site (i.e., group of pages from the same
// registered domain) the user visits.  We default to using a renderer process
// for each site instance (i.e., group of pages from the same registered
// domain with script connections to each other).
const wchar_t kProcessPerSite[] = L"process-per-site";

// Runs plugins inside the renderer process
const wchar_t kInProcessPlugins[]              = L"in-process-plugins";

// Runs the renderer outside the sandbox.
const wchar_t kNoSandbox[]                     = L"no-sandbox";

// Runs the plugin processes inside the sandbox.
const wchar_t kSafePlugins[]                   = L"safe-plugins";

// Excludes these plugins from the plugin sandbox.
// This is a comma separated list of plugin dlls name and activex clsid.
const wchar_t kTrustedPlugins[]                = L"trusted-plugins";

// Runs the security test for the sandbox.
const wchar_t kTestSandbox[]                   = L"test-sandbox";

// Specifies the user data directory, which is where the browser will look
// for all of its state.
const wchar_t kUserDataDir[]                   = L"user-data-dir";

// Specifies that the associated value should be launched in "application" mode.
const wchar_t kApp[]                           = L"app";

// Specifies the file that should be uploaded to the provided application. This
// switch is expected to be used with --app option.
const wchar_t kAppUploadFile[]                 = L"upload-file";

// Specifies if the dom_automation_controller_ needs to be bound in the
// renderer. This binding happens on per-frame basis and hence can potentially
// be a performance bottleneck. One should only enable it when automating
// dom based tests.
const wchar_t kDomAutomationController[]       = L"dom-automation";

// Tells the plugin process the path of the plugin to load
const wchar_t kPluginPath[]                    = L"plugin-path";

// Specifies the flags passed to JS engine
const wchar_t kJavaScriptFlags[]               = L"js-flags";

// The GeoID we should use.  This is normally obtained from the operating system
// during first run and cached in the preferences afterwards.  This is a numeric
// value; see http://msdn.microsoft.com/en-us/library/ms776390.aspx .
const wchar_t kGeoID[]                         = L"geoid";

// The language file that we want to try to open.  Of the form
// language[-country] where language is the 2 letter code from ISO-639.
const wchar_t kLang[]                          = L"lang";

// Will add kDebugOnStart to every child processes. If a value is passed, it
// will be used as a filter to determine if the child process should have the
// kDebugOnStart flag passed on or not.
const wchar_t kDebugChildren[]                 = L"debug-children";

// Will add kWaitForDebugger to every child processes. If a value is passed, it
// will be used as a filter to determine if the child process should have the
// kWaitForDebugger flag passed on or not.
const wchar_t kWaitForDebuggerChildren[]       = L"wait-for-debugger-children";

// Will filter log messages to show only the messages that are prefixed
// with the specified value
const wchar_t kLogFilterPrefix[]               = L"log-filter-prefix";

// Force logging to be enabled.  Logging is disabled by default in release
// builds.
const wchar_t kEnableLogging[]                 = L"enable-logging";

// Force logging to be disabled.  Logging is enabled by default in debug
// builds.
const wchar_t kDisableLogging[]                = L"disable-logging";

// Sets the minimum log level. Valid values are from 0 to 3:
// INFO = 0, WARNING = 1, LOG_ERROR = 2, LOG_FATAL = 3.
const wchar_t kLoggingLevel[]                  = L"log-level";

// Dump any accumualted histograms to the log when browser terminates (requires
// logging to be enabled to really do anything).  Used by developers and test
// scripts.
const wchar_t kDumpHistogramsOnExit[]          = L"dump-histograms-on-exit";

// enable remote debug / automation shell on the specified port
const wchar_t kRemoteShellPort[]               = L"remote-shell-port";

// Runs un-installation steps that were done by chrome first-run.
const wchar_t kUninstall[]                     = L"uninstall";

// Number of entries to show in the omnibox popup.
const wchar_t kOmniBoxPopupCount[]             = L"omnibox-popup-count";

// The value of this switch tells the app to listen for and broadcast
// automation-related messages on IPC channel with the given ID.
const wchar_t kAutomationClientChannelID[]        = L"automation-channel";

// Indicates the last session should be restored on startup. This overrides
// the preferences value and is primarily intended for testing.
const wchar_t kRestoreLastSession[] = L"restore-last-session";

// Chrome supports a playback and record mode.  Record mode saves *everything*
// to the cache.  Playback mode reads data exclusively from the cache.  This
// allows us to record a session into the cache and then replay it at will.
const wchar_t kRecordMode[] = L"record-mode";
const wchar_t kPlaybackMode[] = L"playback-mode";

// Don't record/playback events when using record & playback.
const wchar_t kNoEvents[] = L"no-events";

// Make Windows happy by allowing it to show "Enable access to this program"
// checkbox in Add/Remove Programs->Set Program Access and Defaults. This
// only shows an error box because the only way to hide Chrome is by
// uninstalling it.
const wchar_t kHideIcons[] = L"hide-icons";

const wchar_t kShowIcons[] = L"show-icons";

// Make Chrome default browser
const wchar_t kMakeDefaultBrowser[] = L"make-default-browser";

// Use a specified proxy server, overrides system settings. This switch only
// affects HTTP and HTTPS requests.
const wchar_t kProxyServer[] = L"proxy-server";

// Chrome will support prefetching of DNS information.  Until this becomes
// the default, we'll provide a command line switch.
extern const wchar_t kDnsLogDetails[] = L"dns-log-details";
extern const wchar_t kDnsPrefetchDisable[] = L"dns-prefetch-disable";

// Enables support to debug printing subsystem.
const wchar_t kDebugPrint[] = L"debug-print";

// Allow initialization of all activex controls. This is only to help website
// developers test their controls to see if they are compatible in Chrome.
// Note there's a duplicate value in activex_shared.cc (to avoid
// dependency on chrome module). Please change both locations at the same time.
const wchar_t kAllowAllActiveX[] = L"allow-all-activex";

// Browser flag to disable the web inspector for all renderers.
const wchar_t kDisableDevTools[] = L"disable-dev-tools";

// Enable web inspector for all windows, even if they're part of the browser.
// Allows us to use our dev tools to debug browser windows itself.
const wchar_t kAlwaysEnableDevTools[] = L"always-enable-dev-tools";

// Used to set the value of SessionRestore::num_tabs_to_load_. See
// session_restore.h for details.
const wchar_t kTabCountToLoadOnSessionRestore[] =
    L"tab-count-to-load-on-session-restore";

// Enable dynamic loading of the Memory Profiler DLL, which will trace
// all memory allocations during the run.
const wchar_t kMemoryProfiling[] = L"memory-profile";

// Configure Chrome's memory model.
// Does chrome really need multiple memory models?  No.  But we get a lot
// of concerns from individuals about how the changes work on *their*
// system, and we need to be able to experiment with a few choices.
const wchar_t kMemoryModel[] = L"memory-model";

// By default, cookies are not allowed on file://. They are needed in for
// testing, for example page cycler and layout tests.  See bug 1157243.
const wchar_t kEnableFileCookies[] = L"enable-file-cookies";

// Start the browser maximized, regardless of any previous settings.
const wchar_t kStartMaximized[] = L"start-maximized";

// Spawn threads to watch for excessive delays in specified message loops.
// User should set breakpoints on Alarm() to examine problematic thread.
// Usage:   -enable-watchdog=[ui][io]
// Order of the listed sub-arguments does not matter.
const wchar_t kEnableWatchdog[] = L"enable-watchdog";

// Display the First Run experience when the browser is started, regardless of
// whether or not it's actually the first run.
const wchar_t kFirstRun[] = L"first-run";

// Enable histograming of tasks served by MessageLoop. See about:histograms/Loop
// for results, which show frequency of messages on each thread, including APC
// count, object signalling count, etc.
const wchar_t kMessageLoopHistogrammer[] = L"message-loop-histogrammer";

// Perform importing from another browser. The value associated with this
// setting encodes the target browser and what items to import.
const wchar_t kImport[] = L"import";

// Change the DCHECKS to dump memory and continue instead of crashing.
// This is valid only in Release mode when --enable-dcheck is specified.
const wchar_t kSilentDumpOnDCHECK[] = L"silent-dump-on-dcheck";

// Normally when the user attempts to navigate to a page that was the result of
// a post we prompt to make sure they want to. This switch may be used to
// disable that check. This switch is used during automated testing.
const wchar_t kDisablePromptOnRepost[] = L"disable-prompt-on-repost";

// Disable pop-up blocking.
const wchar_t kDisablePopupBlocking[] = L"disable-popup-blocking";

// Don't execute JavaScript (browser JS like the new tab page still runs).
const wchar_t kDisableJavaScript[] = L"disable-javascript";

// Prevent Java from running.
const wchar_t kDisableJava[] = L"disable-java";

// Prevent plugins from running.
const wchar_t kDisablePlugins[] = L"disable-plugins";

// Prevent images from loading.
const wchar_t kDisableImages[] = L"disable-images";

// Use the low fragmentation heap for the CRT.
const wchar_t kUseLowFragHeapCrt[] = L"use-lf-heap";

#ifndef NDEBUG
// Debug only switch to specify which gears plugin dll to load.
const wchar_t kGearsPluginPathOverride[] = L"gears-plugin-path";
#endif

// Switch to load Gears in the renderer process.
const wchar_t kGearsInRenderer[] = L"gears-in-renderer";

// Enable new HTTP stack.
const wchar_t kUseNewHttp[] = L"new-http";

// Allow loading of the javascript debugger UI from the filesystem.
const wchar_t kJavaScriptDebuggerPath[] = L"javascript-debugger-path";

const wchar_t kEnableP13n[] = L"enable-p13n";

}  // namespace switches

<|endoftext|>


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

#include "chrome/common/slide_animation.h"

#include <math.h>

// How many frames per second to target.
static const int kDefaultFramerateHz = 50;

// How long animations should take by default.
static const int kDefaultDurationMs = 120;

SlideAnimation::SlideAnimation(AnimationDelegate* target)
    : Animation(kDefaultFramerateHz, target),
      target_(target),
      tween_type_(EASE_OUT),
      showing_(false),
      value_start_(0),
      value_end_(0),
      value_current_(0),
      slide_duration_(kDefaultDurationMs) {
}

SlideAnimation::~SlideAnimation() {
}

void SlideAnimation::Reset() {
  Reset(0);
}

void SlideAnimation::Reset(double value) {
  Stop();
  showing_ = static_cast<bool>(value == 1);
  value_current_ = value;
}

void SlideAnimation::Show() {
  // If we're already showing (or fully shown), we have nothing to do.
  if (showing_)
    return;

  showing_ = true;
  value_start_ = value_current_;
  value_end_ = 1.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(1.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_)  {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * (1 - value_current_)));
  Start();
}

void SlideAnimation::Hide() {
  // If we're already hiding (or hidden), we have nothing to do.
  if (!showing_)
    return;

  showing_ = false;
  value_start_ = value_current_;
  value_end_ = 0.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(0.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_) {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * value_current_));
  Start();
}

void SlideAnimation::AnimateToState(double state) {
  if (state > 1.0)
    state = 1.0;

  // Make our animation ease-out.
  switch (tween_type_) {
    case EASE_IN:
      state = pow(state, 2);
      break;
    case EASE_IN_OUT:
      if (state < 0.5)
        state = pow(state * 2, 2) / 2.0;
      else
        state = 1.0 - (pow((state - 1.0) * 2, 2) / 2.0);
      break;
    case FAST_IN_OUT:
      state = (pow(state - 0.5, 3) + 0.125) / 0.25;
      break;
    case NONE:
      // state remains linear.
      break;
    case EASE_OUT_SNAP:
      state = 0.95 * (1.0 - pow(1.0 - state, 2));
      break;
    case EASE_OUT:
    default:
      state = 1.0 - pow(1.0 - state, 2);
      break;
  }

  value_current_ = value_start_ + (value_end_ - value_start_) * state;

  // Implement snapping.
  if (tween_type_ == EASE_OUT_SNAP && abs(value_current_ - value_end_) <= 0.06)
    value_current_ = value_end_;

  // Correct for any overshoot (while state may be capped at 1.0, let's not
  // take any rounding error chances.
  if ((value_end_ >= value_start_ && value_current_ > value_end_) ||
      (value_end_ < value_start_ && value_current_ < value_end_)) {
    value_current_ = value_end_;
  }
}

<commit_msg>Submit Issue 2965 patch by vega.james@gmail.com (jamessan)<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/slide_animation.h"

#include <math.h>

// How many frames per second to target.
static const int kDefaultFramerateHz = 50;

// How long animations should take by default.
static const int kDefaultDurationMs = 120;

SlideAnimation::SlideAnimation(AnimationDelegate* target)
    : Animation(kDefaultFramerateHz, target),
      target_(target),
      tween_type_(EASE_OUT),
      showing_(false),
      value_start_(0),
      value_end_(0),
      value_current_(0),
      slide_duration_(kDefaultDurationMs) {
}

SlideAnimation::~SlideAnimation() {
}

void SlideAnimation::Reset() {
  Reset(0);
}

void SlideAnimation::Reset(double value) {
  Stop();
  showing_ = static_cast<bool>(value == 1);
  value_current_ = value;
}

void SlideAnimation::Show() {
  // If we're already showing (or fully shown), we have nothing to do.
  if (showing_)
    return;

  showing_ = true;
  value_start_ = value_current_;
  value_end_ = 1.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(1.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_)  {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * (1 - value_current_)));
  Start();
}

void SlideAnimation::Hide() {
  // If we're already hiding (or hidden), we have nothing to do.
  if (!showing_)
    return;

  showing_ = false;
  value_start_ = value_current_;
  value_end_ = 0.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(0.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_) {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * value_current_));
  Start();
}

void SlideAnimation::AnimateToState(double state) {
  if (state > 1.0)
    state = 1.0;

  // Make our animation ease-out.
  switch (tween_type_) {
    case EASE_IN:
      state = pow(state, 2);
      break;
    case EASE_IN_OUT:
      if (state < 0.5)
        state = pow(state * 2, 2) / 2.0;
      else
        state = 1.0 - (pow((state - 1.0) * 2, 2) / 2.0);
      break;
    case FAST_IN_OUT:
      state = (pow(state - 0.5, 3) + 0.125) / 0.25;
      break;
    case NONE:
      // state remains linear.
      break;
    case EASE_OUT_SNAP:
      state = 0.95 * (1.0 - pow(1.0 - state, 2));
      break;
    case EASE_OUT:
    default:
      state = 1.0 - pow(1.0 - state, 2);
      break;
  }

  value_current_ = value_start_ + (value_end_ - value_start_) * state;

  // Implement snapping.
  if (tween_type_ == EASE_OUT_SNAP && fabs(value_current_ - value_end_) <= 0.06)
    value_current_ = value_end_;

  // Correct for any overshoot (while state may be capped at 1.0, let's not
  // take any rounding error chances.
  if ((value_end_ >= value_start_ && value_current_ > value_end_) ||
      (value_end_ < value_start_ && value_current_ < value_end_)) {
    value_current_ = value_end_;
  }
}
<|endoftext|>


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

#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#include <algorithm>

#include "chrome/renderer/render_thread.h"

#include "base/shared_memory.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/notification_service.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include <vector>
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#include "webkit/glue/weburlrequest.h"
#endif
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/user_script_slave.h"
#include "chrome/renderer/visitedlink_slave.h"
#include "webkit/glue/cache_manager.h"

RenderThread* g_render_thread;

static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;

// V8 needs a 1MB stack size.
static const size_t kStackSize = 1024 * 1024;

//-----------------------------------------------------------------------------
// Methods below are only called on the owner's thread:

RenderThread::RenderThread(const std::wstring& channel_name)
    : Thread("Chrome_RenderThread"),
      owner_loop_(MessageLoop::current()),
      channel_name_(channel_name),
      visited_link_slave_(NULL),
      user_script_slave_(NULL),
      render_dns_master_(NULL),
      in_send_(0) {
  DCHECK(owner_loop_);
  base::Thread::Options options;
  options.stack_size = kStackSize;
  // When we run plugins in process, we actually run them on the render thread,
  // which means that we need to make the render thread pump UI events.
  if (RenderProcess::ShouldLoadPluginsInProcess())
    options.message_loop_type = MessageLoop::TYPE_UI;
  StartWithOptions(options);
}

RenderThread::~RenderThread() {
  Stop();
}

void RenderThread::OnChannelError() {
  owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

bool RenderThread::Send(IPC::Message* msg) {
  in_send_++;
  bool rv = channel_->Send(msg);
  in_send_--;
  return rv;
}

void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->AddFilter(filter);
}

void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->RemoveFilter(filter);
}

void RenderThread::Resolve(const char* name, size_t length) {
// TODO(port)
#if defined(OS_WIN)
  return render_dns_master_->Resolve(name, length);
#else
  NOTIMPLEMENTED();
#endif
}

void RenderThread::AddRoute(int32 routing_id,
                            IPC::Channel::Listener* listener) {
  DCHECK(MessageLoop::current() == message_loop());

  // This corresponds to the AddRoute call done in CreateView.
  router_.AddRoute(routing_id, listener);
}

void RenderThread::RemoveRoute(int32 routing_id) {
  DCHECK(MessageLoop::current() == message_loop());

  router_.RemoveRoute(routing_id);
}

void RenderThread::Init() {
  DCHECK(!g_render_thread);
  g_render_thread = this;

  notification_service_.reset(new NotificationService);

  cache_stats_factory_.reset(
      new ScopedRunnableMethodFactory<RenderThread>(this));

  channel_.reset(new IPC::SyncChannel(channel_name_,
      IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true,
      RenderProcess::GetShutDownEvent()));

#if defined(OS_WIN)
  // The renderer thread should wind-up COM.
  CoInitialize(0);
#endif

  visited_link_slave_ = new VisitedLinkSlave();
  user_script_slave_ = new UserScriptSlave();
  render_dns_master_.reset(new RenderDnsMaster());

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(this);
#endif
}

void RenderThread::CleanUp() {
  DCHECK(g_render_thread == this);
  g_render_thread = NULL;

  // Need to destruct the SyncChannel to the browser before we go away because
  // it caches a pointer to this thread.
  channel_.reset();

// TODO(port)
#if defined(OS_WIN)
  // Clean up plugin channels before this thread goes away.
  PluginChannelBase::CleanupChannels();
#endif

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(NULL);
#endif

  notification_service_.reset();

  delete visited_link_slave_;
  visited_link_slave_ = NULL;

  delete user_script_slave_;
  user_script_slave_ = NULL;

#if defined(OS_WIN)
  CoUninitialize();
#endif
}

void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
  DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
  visited_link_slave_->Init(table);
}

void RenderThread::OnUpdateUserScripts(
    base::SharedMemoryHandle scripts) {
  DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
  user_script_slave_->UpdateScripts(scripts);
}

void RenderThread::OnMessageReceived(const IPC::Message& msg) {
  // NOTE: We could subclass router_ to intercept OnControlMessageReceived, but
  // it seems simpler to just process any control messages that we care about
  // up-front and then send the rest of the messages onto router_.

  if (msg.routing_id() == MSG_ROUTING_CONTROL) {
    IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
      IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
      IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
      // TODO(port): removed from render_messages_internal.h;
      // is there a new non-windows message I should add here?
      IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
      IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
      IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
                          OnGetCacheResourceStats)
      IPC_MESSAGE_HANDLER(ViewMsg_PluginMessage, OnPluginMessage)
      IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts,
                          OnUpdateUserScripts)
      // send the rest to the router
      IPC_MESSAGE_UNHANDLED(router_.OnMessageReceived(msg))
    IPC_END_MESSAGE_MAP()
  } else {
    router_.OnMessageReceived(msg);
  }
}

void RenderThread::OnPluginMessage(const FilePath& plugin_path,
                                   const std::vector<uint8>& data) {
  if (!ChromePluginLib::IsInitialized()) {
    return;
  }
  CHECK(ChromePluginLib::IsPluginThread());
  ChromePluginLib *chrome_plugin = ChromePluginLib::Find(plugin_path);
  if (chrome_plugin) {
    void *data_ptr = const_cast<void*>(reinterpret_cast<const void*>(&data[0]));
    uint32 data_len = static_cast<uint32>(data.size());
    chrome_plugin->functions().on_message(data_ptr, data_len);
  }
}

void RenderThread::OnSetNextPageID(int32 next_page_id) {
  // This should only be called at process initialization time, so we shouldn't
  // have to worry about thread-safety.
  // TODO(port)
#if !defined(OS_LINUX)
  RenderView::SetNextPageID(next_page_id);
#endif
}

void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
                                   ModalDialogEvent modal_dialog_event,
                                   const WebPreferences& webkit_prefs,
                                   int32 view_id) {
  // When bringing in render_view, also bring in webkit's glue and jsbindings.
  base::WaitableEvent* waitable_event = new base::WaitableEvent(
#if defined(OS_WIN)
      modal_dialog_event.event);
#else
      true, false);
#endif

#if defined(OS_MACOSX)
  // TODO(jrg): causes a crash.
  if (0)
#endif
  // TODO(darin): once we have a RenderThread per RenderView, this will need to
  // change to assert that we are not creating more than one view.
  RenderView::Create(
      this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs,
      new SharedRenderViewCounter(0), view_id);
}

void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
                                        size_t max_dead_capacity,
                                        size_t capacity) {
#if defined(OS_WIN)
  CacheManager::SetCapacities(min_dead_capacity, max_dead_capacity, capacity);
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::OnGetCacheResourceStats() {
#if defined(OS_WIN)
  CacheManager::ResourceTypeStats stats;
  CacheManager::GetResourceTypeStats(&stats);
  Send(new ViewHostMsg_ResourceTypeStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStats() {
#if defined(OS_WIN)
  CacheManager::UsageStats stats;
  CacheManager::GetUsageStats(&stats);
  Send(new ViewHostMsg_UpdatedCacheStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStatsLater() {
  // Rate limit informing the host of our cache stats.
  if (!cache_stats_factory_->empty())
    return;

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      cache_stats_factory_->NewRunnableMethod(
          &RenderThread::InformHostOfCacheStats),
      kCacheStatsDelayMS);
}
<commit_msg>Fix totally broken include set.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#include <algorithm>

#include "chrome/renderer/render_thread.h"

#include "base/shared_memory.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/notification_service.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include <vector>
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#include "webkit/glue/weburlrequest.h"
#endif
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/user_script_slave.h"
#include "chrome/renderer/visitedlink_slave.h"
#include "webkit/glue/cache_manager.h"

RenderThread* g_render_thread;

static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;

// V8 needs a 1MB stack size.
static const size_t kStackSize = 1024 * 1024;

//-----------------------------------------------------------------------------
// Methods below are only called on the owner's thread:

RenderThread::RenderThread(const std::wstring& channel_name)
    : Thread("Chrome_RenderThread"),
      owner_loop_(MessageLoop::current()),
      channel_name_(channel_name),
      visited_link_slave_(NULL),
      user_script_slave_(NULL),
      render_dns_master_(NULL),
      in_send_(0) {
  DCHECK(owner_loop_);
  base::Thread::Options options;
  options.stack_size = kStackSize;
  // When we run plugins in process, we actually run them on the render thread,
  // which means that we need to make the render thread pump UI events.
  if (RenderProcess::ShouldLoadPluginsInProcess())
    options.message_loop_type = MessageLoop::TYPE_UI;
  StartWithOptions(options);
}

RenderThread::~RenderThread() {
  Stop();
}

void RenderThread::OnChannelError() {
  owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

bool RenderThread::Send(IPC::Message* msg) {
  in_send_++;
  bool rv = channel_->Send(msg);
  in_send_--;
  return rv;
}

void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->AddFilter(filter);
}

void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->RemoveFilter(filter);
}

void RenderThread::Resolve(const char* name, size_t length) {
// TODO(port)
#if defined(OS_WIN)
  return render_dns_master_->Resolve(name, length);
#else
  NOTIMPLEMENTED();
#endif
}

void RenderThread::AddRoute(int32 routing_id,
                            IPC::Channel::Listener* listener) {
  DCHECK(MessageLoop::current() == message_loop());

  // This corresponds to the AddRoute call done in CreateView.
  router_.AddRoute(routing_id, listener);
}

void RenderThread::RemoveRoute(int32 routing_id) {
  DCHECK(MessageLoop::current() == message_loop());

  router_.RemoveRoute(routing_id);
}

void RenderThread::Init() {
  DCHECK(!g_render_thread);
  g_render_thread = this;

  notification_service_.reset(new NotificationService);

  cache_stats_factory_.reset(
      new ScopedRunnableMethodFactory<RenderThread>(this));

  channel_.reset(new IPC::SyncChannel(channel_name_,
      IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true,
      RenderProcess::GetShutDownEvent()));

#if defined(OS_WIN)
  // The renderer thread should wind-up COM.
  CoInitialize(0);
#endif

  visited_link_slave_ = new VisitedLinkSlave();
  user_script_slave_ = new UserScriptSlave();
  render_dns_master_.reset(new RenderDnsMaster());

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(this);
#endif
}

void RenderThread::CleanUp() {
  DCHECK(g_render_thread == this);
  g_render_thread = NULL;

  // Need to destruct the SyncChannel to the browser before we go away because
  // it caches a pointer to this thread.
  channel_.reset();

// TODO(port)
#if defined(OS_WIN)
  // Clean up plugin channels before this thread goes away.
  PluginChannelBase::CleanupChannels();
#endif

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(NULL);
#endif

  notification_service_.reset();

  delete visited_link_slave_;
  visited_link_slave_ = NULL;

  delete user_script_slave_;
  user_script_slave_ = NULL;

#if defined(OS_WIN)
  CoUninitialize();
#endif
}

void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
  DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
  visited_link_slave_->Init(table);
}

void RenderThread::OnUpdateUserScripts(
    base::SharedMemoryHandle scripts) {
  DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
  user_script_slave_->UpdateScripts(scripts);
}

void RenderThread::OnMessageReceived(const IPC::Message& msg) {
  // NOTE: We could subclass router_ to intercept OnControlMessageReceived, but
  // it seems simpler to just process any control messages that we care about
  // up-front and then send the rest of the messages onto router_.

  if (msg.routing_id() == MSG_ROUTING_CONTROL) {
    IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
      IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
      IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
      // TODO(port): removed from render_messages_internal.h;
      // is there a new non-windows message I should add here?
      IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
      IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
      IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
                          OnGetCacheResourceStats)
      IPC_MESSAGE_HANDLER(ViewMsg_PluginMessage, OnPluginMessage)
      IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts,
                          OnUpdateUserScripts)
      // send the rest to the router
      IPC_MESSAGE_UNHANDLED(router_.OnMessageReceived(msg))
    IPC_END_MESSAGE_MAP()
  } else {
    router_.OnMessageReceived(msg);
  }
}

void RenderThread::OnPluginMessage(const FilePath& plugin_path,
                                   const std::vector<uint8>& data) {
  if (!ChromePluginLib::IsInitialized()) {
    return;
  }
  CHECK(ChromePluginLib::IsPluginThread());
  ChromePluginLib *chrome_plugin = ChromePluginLib::Find(plugin_path);
  if (chrome_plugin) {
    void *data_ptr = const_cast<void*>(reinterpret_cast<const void*>(&data[0]));
    uint32 data_len = static_cast<uint32>(data.size());
    chrome_plugin->functions().on_message(data_ptr, data_len);
  }
}

void RenderThread::OnSetNextPageID(int32 next_page_id) {
  // This should only be called at process initialization time, so we shouldn't
  // have to worry about thread-safety.
  // TODO(port)
#if !defined(OS_LINUX)
  RenderView::SetNextPageID(next_page_id);
#endif
}

void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
                                   ModalDialogEvent modal_dialog_event,
                                   const WebPreferences& webkit_prefs,
                                   int32 view_id) {
  // When bringing in render_view, also bring in webkit's glue and jsbindings.
  base::WaitableEvent* waitable_event = new base::WaitableEvent(
#if defined(OS_WIN)
      modal_dialog_event.event);
#else
      true, false);
#endif

#if defined(OS_MACOSX)
  // TODO(jrg): causes a crash.
  if (0)
#endif
  // TODO(darin): once we have a RenderThread per RenderView, this will need to
  // change to assert that we are not creating more than one view.
  RenderView::Create(
      this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs,
      new SharedRenderViewCounter(0), view_id);
}

void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
                                        size_t max_dead_capacity,
                                        size_t capacity) {
#if defined(OS_WIN)
  CacheManager::SetCapacities(min_dead_capacity, max_dead_capacity, capacity);
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::OnGetCacheResourceStats() {
#if defined(OS_WIN)
  CacheManager::ResourceTypeStats stats;
  CacheManager::GetResourceTypeStats(&stats);
  Send(new ViewHostMsg_ResourceTypeStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStats() {
#if defined(OS_WIN)
  CacheManager::UsageStats stats;
  CacheManager::GetUsageStats(&stats);
  Send(new ViewHostMsg_UpdatedCacheStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStatsLater() {
  // Rate limit informing the host of our cache stats.
  if (!cache_stats_factory_->empty())
    return;

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      cache_stats_factory_->NewRunnableMethod(
          &RenderThread::InformHostOfCacheStats),
      kCacheStatsDelayMS);
}
<|endoftext|>


<commit_before>/* Copyright (c) 2018 ARM Limited
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstring>
#include "KVMap.h"
#include "KVStore.h"
#include "TDBStore.h"
#include "psa_prot_internal_storage.h"
#include "pits_impl.h"
#include "mbed_error.h"

#ifdef   __cplusplus
extern "C"
{
#endif

using namespace mbed;

#define STR_EXPAND(tok)                 #tok

// Maximum length of filename we use for kvstore API.
// uid: 6; delimiter: 1; pid: 6; str terminator: 1
#define PSA_ITS_FILENAME_MAX_LEN        14

const uint8_t base64_coding_table[] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3',
    '4', '5', '6', '7', '8', '9', '+', '-'
};

/*
 * \brief Get default KVStore instance for internal flesh storage
 *
 * \return valid pointer to KVStore
 */
static KVStore *get_kvstore_instance(void)
{
    KVMap &kv_map = KVMap::get_instance();

    KVStore *kvstore = kv_map.get_internal_kv_instance(STR_EXPAND(MBED_CONF_STORAGE_DEFAULT_KV));
    if (!kvstore) {
        // Can only happen due to system misconfiguration.
        // Thus considered as unrecoverable error for runtime.
        error("Failed getting kvstore instance\n");
    }
    return kvstore;
}

/*
 * \brief Convert KVStore stauts codes to PSA internal storage status codes
 *
 * \param[in] status - KVStore status code
 * \return PSA internal storage status code
 */
static psa_its_status_t convert_status(int status)
{
    switch (status) {
        case MBED_SUCCESS:
            return PSA_ITS_SUCCESS;
        case MBED_ERROR_WRITE_PROTECTED:
            return PSA_ITS_ERROR_WRITE_ONCE;
        case MBED_ERROR_MEDIA_FULL:
            return PSA_ITS_ERROR_INSUFFICIENT_SPACE;
        case MBED_ERROR_ITEM_NOT_FOUND:
            return PSA_ITS_ERROR_KEY_NOT_FOUND;
        default:
            return PSA_ITS_ERROR_STORAGE_FAILURE;
    }
}

/*
 * \breif Generate KVStore file name
 *
 * Generate KVStore file name by Base64 encoding PID and UID with a delimiter.
 * Delimiter is required for determining between PID and UID.
 *
 * \param[out] tdb_filename - pointer to a buffer for the file name
 * \param[in]  tdb_filename_size - output buffer size
 * \param[in]  uid - PSA internal storage unique ID
 * \param[in]  pid - owner PSA partition ID
 */
static void generate_fn(char *tdb_filename, uint32_t tdb_filename_size, uint32_t uid, uint32_t pid)
{
    MBED_ASSERT(tdb_filename != NULL);
    MBED_ASSERT(tdb_filename_size == PSA_ITS_FILENAME_MAX_LEN);

    uint8_t filename_idx = 0;

    // Iterate on UID; each time convert 6 bits of UID into a character; first iteration must be done
    do {
        tdb_filename[filename_idx++] = base64_coding_table[uid & 0x3F];
        uid = uid >> 6;
    } while (uid != 0);

    // Write delimiter
    tdb_filename[filename_idx++] = '#';

    // Iterate on PID; each time convert 6 bits of PID into a character; first iteration must be done
    do {
        tdb_filename[filename_idx++] = base64_coding_table[pid & 0x3F];
        pid = pid >> 6;
    } while (pid != 0);

    tdb_filename[filename_idx++] = '\0';
    MBED_ASSERT(filename_idx <= PSA_ITS_FILENAME_MAX_LEN);
}

psa_its_status_t psa_its_set_impl(uint32_t pid, uint32_t uid, uint32_t data_length, const void *p_data, psa_its_create_flags_t create_flags)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    if ((create_flags != 0) && (create_flags != PSA_ITS_WRITE_ONCE_FLAG)) {
        return PSA_ITS_ERROR_FLAGS_NOT_SUPPORTED;
    }

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    uint32_t kv_create_flags = 0;
    if (create_flags & PSA_ITS_WRITE_ONCE_FLAG) {
        kv_create_flags = KVStore::WRITE_ONCE_FLAG;
    }

    int status = kvstore->set(kv_key, p_data, data_length, kv_create_flags);

    return convert_status(status);
}

psa_its_status_t psa_its_get_impl(uint32_t pid, uint32_t uid, uint32_t data_offset, uint32_t data_length, void *p_data)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    KVStore::info_t kv_info;
    int status = kvstore->get_info(kv_key, &kv_info);

    if (status == MBED_SUCCESS) {
        if (data_offset > kv_info.size) {
            return PSA_PS_ERROR_OFFSET_INVALID;
        }

        // Verify (size + offset) does not wrap around
        if (data_length + data_offset < data_length) {
            return PSA_ITS_ERROR_INCORRECT_SIZE;
        }

        if (data_offset + data_length > kv_info.size) {
            return PSA_ITS_ERROR_INCORRECT_SIZE;
        }

        size_t actual_size = 0;
        status = kvstore->get(kv_key, p_data, data_length, &actual_size, data_offset);

        if (status == MBED_SUCCESS) {
            if (actual_size < data_length) {
                status = PSA_ITS_ERROR_INCORRECT_SIZE;
            }
        }
    }

    return convert_status(status);
}

psa_its_status_t psa_its_get_info_impl(uint32_t pid, uint32_t uid, struct psa_its_info_t *p_info)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    KVStore::info_t kv_info;
    int status = kvstore->get_info(kv_key, &kv_info);

    if (status == MBED_SUCCESS) {
        p_info->flags = 0;
        if (kv_info.flags & KVStore::WRITE_ONCE_FLAG) {
            p_info->flags |= PSA_ITS_WRITE_ONCE_FLAG;
        }
        p_info->size = (uint32_t)(kv_info.size);   // kv_info.size is of type size_t
    }

    return convert_status(status);
}

psa_its_status_t psa_its_remove_impl(uint32_t pid, uint32_t uid)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    int status = kvstore->remove(kv_key);

    return convert_status(status);
}

#ifdef   __cplusplus
}
#endif
<commit_msg>Replace PID and UID order in file name<commit_after>/* Copyright (c) 2018 ARM Limited
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cstring>
#include "KVMap.h"
#include "KVStore.h"
#include "TDBStore.h"
#include "psa_prot_internal_storage.h"
#include "pits_impl.h"
#include "mbed_error.h"

#ifdef   __cplusplus
extern "C"
{
#endif

using namespace mbed;

#define STR_EXPAND(tok)                 #tok

// Maximum length of filename we use for kvstore API.
// uid: 6; delimiter: 1; pid: 6; str terminator: 1
#define PSA_ITS_FILENAME_MAX_LEN        14

const uint8_t base64_coding_table[] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
    'w', 'x', 'y', 'z', '0', '1', '2', '3',
    '4', '5', '6', '7', '8', '9', '+', '-'
};

/*
 * \brief Get default KVStore instance for internal flesh storage
 *
 * \return valid pointer to KVStore
 */
static KVStore *get_kvstore_instance(void)
{
    KVMap &kv_map = KVMap::get_instance();

    KVStore *kvstore = kv_map.get_internal_kv_instance(STR_EXPAND(MBED_CONF_STORAGE_DEFAULT_KV));
    if (!kvstore) {
        // Can only happen due to system misconfiguration.
        // Thus considered as unrecoverable error for runtime.
        error("Failed getting kvstore instance\n");
    }
    return kvstore;
}

/*
 * \brief Convert KVStore stauts codes to PSA internal storage status codes
 *
 * \param[in] status - KVStore status code
 * \return PSA internal storage status code
 */
static psa_its_status_t convert_status(int status)
{
    switch (status) {
        case MBED_SUCCESS:
            return PSA_ITS_SUCCESS;
        case MBED_ERROR_WRITE_PROTECTED:
            return PSA_ITS_ERROR_WRITE_ONCE;
        case MBED_ERROR_MEDIA_FULL:
            return PSA_ITS_ERROR_INSUFFICIENT_SPACE;
        case MBED_ERROR_ITEM_NOT_FOUND:
            return PSA_ITS_ERROR_KEY_NOT_FOUND;
        default:
            return PSA_ITS_ERROR_STORAGE_FAILURE;
    }
}

/*
 * \breif Generate KVStore file name
 *
 * Generate KVStore file name by Base64 encoding PID and UID with a delimiter.
 * Delimiter is required for determining between PID and UID.
 *
 * \param[out] tdb_filename - pointer to a buffer for the file name
 * \param[in]  tdb_filename_size - output buffer size
 * \param[in]  uid - PSA internal storage unique ID
 * \param[in]  pid - owner PSA partition ID
 */
static void generate_fn(char *tdb_filename, uint32_t tdb_filename_size, uint32_t uid, uint32_t pid)
{
    MBED_ASSERT(tdb_filename != NULL);
    MBED_ASSERT(tdb_filename_size == PSA_ITS_FILENAME_MAX_LEN);

    uint8_t filename_idx = 0;

    // Iterate on PID; each time convert 6 bits of PID into a character; first iteration must be done
    do {
        tdb_filename[filename_idx++] = base64_coding_table[pid & 0x3F];
        pid = pid >> 6;
    } while (pid != 0);

    // Write delimiter
    tdb_filename[filename_idx++] = '#';

    // Iterate on UID; each time convert 6 bits of UID into a character; first iteration must be done
    do {
        tdb_filename[filename_idx++] = base64_coding_table[uid & 0x3F];
        uid = uid >> 6;
    } while (uid != 0);

    tdb_filename[filename_idx++] = '\0';
    MBED_ASSERT(filename_idx <= PSA_ITS_FILENAME_MAX_LEN);
}

psa_its_status_t psa_its_set_impl(uint32_t pid, uint32_t uid, uint32_t data_length, const void *p_data, psa_its_create_flags_t create_flags)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    if ((create_flags != 0) && (create_flags != PSA_ITS_WRITE_ONCE_FLAG)) {
        return PSA_ITS_ERROR_FLAGS_NOT_SUPPORTED;
    }

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    uint32_t kv_create_flags = 0;
    if (create_flags & PSA_ITS_WRITE_ONCE_FLAG) {
        kv_create_flags = KVStore::WRITE_ONCE_FLAG;
    }

    int status = kvstore->set(kv_key, p_data, data_length, kv_create_flags);

    return convert_status(status);
}

psa_its_status_t psa_its_get_impl(uint32_t pid, uint32_t uid, uint32_t data_offset, uint32_t data_length, void *p_data)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    KVStore::info_t kv_info;
    int status = kvstore->get_info(kv_key, &kv_info);

    if (status == MBED_SUCCESS) {
        if (data_offset > kv_info.size) {
            return PSA_PS_ERROR_OFFSET_INVALID;
        }

        // Verify (size + offset) does not wrap around
        if (data_length + data_offset < data_length) {
            return PSA_ITS_ERROR_INCORRECT_SIZE;
        }

        if (data_offset + data_length > kv_info.size) {
            return PSA_ITS_ERROR_INCORRECT_SIZE;
        }

        size_t actual_size = 0;
        status = kvstore->get(kv_key, p_data, data_length, &actual_size, data_offset);

        if (status == MBED_SUCCESS) {
            if (actual_size < data_length) {
                status = PSA_ITS_ERROR_INCORRECT_SIZE;
            }
        }
    }

    return convert_status(status);
}

psa_its_status_t psa_its_get_info_impl(uint32_t pid, uint32_t uid, struct psa_its_info_t *p_info)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    KVStore::info_t kv_info;
    int status = kvstore->get_info(kv_key, &kv_info);

    if (status == MBED_SUCCESS) {
        p_info->flags = 0;
        if (kv_info.flags & KVStore::WRITE_ONCE_FLAG) {
            p_info->flags |= PSA_ITS_WRITE_ONCE_FLAG;
        }
        p_info->size = (uint32_t)(kv_info.size);   // kv_info.size is of type size_t
    }

    return convert_status(status);
}

psa_its_status_t psa_its_remove_impl(uint32_t pid, uint32_t uid)
{
    KVStore *kvstore = get_kvstore_instance();
    MBED_ASSERT(kvstore);

    // Generate KVStore key
    char kv_key[PSA_ITS_FILENAME_MAX_LEN] = {'\0'};
    generate_fn(kv_key, PSA_ITS_FILENAME_MAX_LEN, uid, pid);

    int status = kvstore->remove(kv_key);

    return convert_status(status);
}

#ifdef   __cplusplus
}
#endif
<|endoftext|>


<commit_before><commit_msg>const correctness<commit_after><|endoftext|>


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

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "LoadDataReaction.h"

#include "ActiveObjects.h"
#include "DataSource.h"
#include "EmdFormat.h"
#include "ModuleManager.h"
#include "RecentFilesMenu.h"
#include "Utilities.h"

#include "pqActiveObjects.h"
#include "pqLoadDataReaction.h"
#include "pqPipelineSource.h"
#include "pqProxyWidgetDialog.h"
#include "pqRenderView.h"
#include "pqSMAdaptor.h"
#include "vtkImageData.h"
#include "vtkNew.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMStringVectorProperty.h"
#include "vtkSmartPointer.h"
#include "vtkTrivialProducer.h"

#include <QFileDialog>
#include <QFileInfo>

namespace tomviz {

LoadDataReaction::LoadDataReaction(QAction* parentObject)
  : Superclass(parentObject)
{
}

LoadDataReaction::~LoadDataReaction()
{
}

void LoadDataReaction::onTriggered()
{
  loadData();
}

QList<DataSource*> LoadDataReaction::loadData()
{
  vtkNew<vtkSMParaViewPipelineController> controller;

  QStringList filters;
  filters
    << "Common file types (*.emd *.jpg *.jpeg *.png *.tiff *.tif *.raw"
       " *.dat *.bin *.txt *.mhd *.mha *.mrc *.st *.rec *.ali *.xmf *.xdmf)"
    << "EMD (*.emd)"
    << "JPeg Image files (*.jpg *.jpeg)"
    << "PNG Image files (*.png)"
    << "TIFF Image files (*.tiff *.tif)"
    << "OME-TIFF Image files (*.ome.tif)"
    << "Raw data files (*.raw *.dat *.bin)"
    << "Meta Image files (*.mhd *.mha)"
    << "MRC files (*.mrc *.st *.rec *.ali)"
    << "XDMF files (*.xmf *.xdmf)"
    << "Text files (*.txt)"
    << "All files (*.*)";

  QFileDialog dialog(nullptr);
  dialog.setFileMode(QFileDialog::ExistingFiles);
  dialog.setNameFilters(filters);
  dialog.setObjectName("FileOpenDialog-tomviz"); // avoid name collision?

  QList<DataSource*> dataSources;
  if (dialog.exec()) {
    QStringList filenames = dialog.selectedFiles();
    dataSources << loadData(filenames);
  }

  return dataSources;
}

DataSource* LoadDataReaction::loadData(const QString& fileName)
{
  QStringList fileNames;
  fileNames << fileName;

  return loadData(fileNames);
}

DataSource* LoadDataReaction::loadData(const QStringList& fileNames)
{
  DataSource* dataSource(nullptr);
  QString fileName;
  if (fileNames.size() > 0) {
    fileName = fileNames[0];
  }
  QFileInfo info(fileName);
  if (info.suffix() == "emd") {
    // Load the file using our simple EMD class.
    EmdFormat emdFile;
    vtkNew<vtkImageData> imageData;
    emdFile.read(fileName.toLatin1().data(), imageData.Get());

    dataSource = createDataSource(imageData.Get());
    dataSource->originalDataSource()->SetAnnotation(Attributes::FILENAME,
                                                    fileName.toLatin1().data());
    LoadDataReaction::dataSourceAdded(dataSource);
  } else if (info.completeSuffix().endsWith("ome.tif")) {
    auto pxm = tomviz::ActiveObjects::instance().proxyManager();
    vtkSmartPointer<vtkSMProxy> source;
    source.TakeReference(pxm->NewProxy("sources", "OMETIFFReader"));
    QString pname = vtkSMCoreUtilities::GetFileNameProperty(source);
    vtkSMStringVectorProperty *prop = vtkSMStringVectorProperty::SafeDownCast(source->GetProperty(pname.toUtf8().data()));
    pqSMAdaptor::setElementProperty(prop, fileName);
    source->UpdateVTKObjects();

    dataSource = createDataSource(source);
    // The dataSource may be NULL if the user cancelled the action.
    if (dataSource) {
      RecentFilesMenu::pushDataReader(dataSource, source);
    }
  } else {
    // Use ParaView's file load infrastructure.
    pqPipelineSource* reader = pqLoadDataReaction::loadData(fileNames);

    if (!reader) {
      return nullptr;
    }

    dataSource = createDataSource(reader->getProxy());
    // The dataSource may be NULL if the user cancelled the action.
    if (dataSource) {
      RecentFilesMenu::pushDataReader(dataSource, reader->getProxy());
    }
    vtkNew<vtkSMParaViewPipelineController> controller;
    controller->UnRegisterProxy(reader->getProxy());
  }

  return dataSource;
}

DataSource* LoadDataReaction::createDataSource(vtkSMProxy* reader)
{
  // Prompt user for reader configuration.
  pqProxyWidgetDialog dialog(reader);
  dialog.setObjectName("ConfigureReaderDialog");
  dialog.setWindowTitle("Configure Reader Parameters");
  if (dialog.hasVisibleWidgets() == false ||
      dialog.exec() == QDialog::Accepted) {
    DataSource* previousActiveDataSource =
      ActiveObjects::instance().activeDataSource();

    DataSource* dataSource =
      new DataSource(vtkSMSourceProxy::SafeDownCast(reader));
    // do whatever we need to do with a new data source.
    LoadDataReaction::dataSourceAdded(dataSource);
    if (!previousActiveDataSource) {
      pqRenderView* renderView =
        qobject_cast<pqRenderView*>(pqActiveObjects::instance().activeView());
      if (renderView) {
        tomviz::createCameraOrbit(dataSource->producer(),
                                  renderView->getRenderViewProxy());
      }
    }
    return dataSource;
  }
  return nullptr;
}

DataSource* LoadDataReaction::createDataSource(vtkImageData* imageData)
{
  auto pxm = tomviz::ActiveObjects::instance().proxyManager();
  vtkSmartPointer<vtkSMProxy> source;
  source.TakeReference(pxm->NewProxy("sources", "TrivialProducer"));
  auto tp = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject());
  tp->SetOutput(imageData);
  source->SetAnnotation("tomviz.Type", "DataSource");

  auto dataSource = new DataSource(vtkSMSourceProxy::SafeDownCast(source));
  return dataSource;
}

void LoadDataReaction::dataSourceAdded(DataSource* dataSource)
{
  bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
  ActiveObjects::instance().setMoveObjectsMode(false);
  ModuleManager::instance().addDataSource(dataSource);

  ActiveObjects::instance().createRenderViewIfNeeded();
  ActiveObjects::instance().setActiveViewToFirstRenderView();

  vtkSMViewProxy* view = ActiveObjects::instance().activeView();

  // Create an outline module for the source in the active view.
  if (Module* module = ModuleManager::instance().createAndAddModule(
        "Outline", dataSource, view)) {
    ActiveObjects::instance().setActiveModule(module);
  }
  if (Module* module = ModuleManager::instance().createAndAddModule(
        "Orthogonal Slice", dataSource, view)) {
    ActiveObjects::instance().setActiveModule(module);
  }
  ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
}

} // end of namespace tomviz
<commit_msg>Handle failed readers by not creating data source<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "LoadDataReaction.h"

#include "ActiveObjects.h"
#include "DataSource.h"
#include "EmdFormat.h"
#include "ModuleManager.h"
#include "RecentFilesMenu.h"
#include "Utilities.h"

#include "pqActiveObjects.h"
#include "pqLoadDataReaction.h"
#include "pqPipelineSource.h"
#include "pqProxyWidgetDialog.h"
#include "pqRenderView.h"
#include "pqSMAdaptor.h"
#include "vtkImageData.h"
#include "vtkNew.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMStringVectorProperty.h"
#include "vtkSmartPointer.h"
#include "vtkTrivialProducer.h"

#include <QDebug>
#include <QFileDialog>
#include <QFileInfo>

namespace tomviz {

LoadDataReaction::LoadDataReaction(QAction* parentObject)
  : Superclass(parentObject)
{
}

LoadDataReaction::~LoadDataReaction()
{
}

void LoadDataReaction::onTriggered()
{
  loadData();
}

QList<DataSource*> LoadDataReaction::loadData()
{
  vtkNew<vtkSMParaViewPipelineController> controller;

  QStringList filters;
  filters
    << "Common file types (*.emd *.jpg *.jpeg *.png *.tiff *.tif *.raw"
       " *.dat *.bin *.txt *.mhd *.mha *.mrc *.st *.rec *.ali *.xmf *.xdmf)"
    << "EMD (*.emd)"
    << "JPeg Image files (*.jpg *.jpeg)"
    << "PNG Image files (*.png)"
    << "TIFF Image files (*.tiff *.tif)"
    << "OME-TIFF Image files (*.ome.tif)"
    << "Raw data files (*.raw *.dat *.bin)"
    << "Meta Image files (*.mhd *.mha)"
    << "MRC files (*.mrc *.st *.rec *.ali)"
    << "XDMF files (*.xmf *.xdmf)"
    << "Text files (*.txt)"
    << "All files (*.*)";

  QFileDialog dialog(nullptr);
  dialog.setFileMode(QFileDialog::ExistingFiles);
  dialog.setNameFilters(filters);
  dialog.setObjectName("FileOpenDialog-tomviz"); // avoid name collision?

  QList<DataSource*> dataSources;
  if (dialog.exec()) {
    QStringList filenames = dialog.selectedFiles();
    dataSources << loadData(filenames);
  }

  return dataSources;
}

DataSource* LoadDataReaction::loadData(const QString& fileName)
{
  QStringList fileNames;
  fileNames << fileName;

  return loadData(fileNames);
}

DataSource* LoadDataReaction::loadData(const QStringList& fileNames)
{
  DataSource* dataSource(nullptr);
  QString fileName;
  if (fileNames.size() > 0) {
    fileName = fileNames[0];
  }
  QFileInfo info(fileName);
  if (info.suffix() == "emd") {
    // Load the file using our simple EMD class.
    EmdFormat emdFile;
    vtkNew<vtkImageData> imageData;
    emdFile.read(fileName.toLatin1().data(), imageData.Get());

    dataSource = createDataSource(imageData.Get());
    dataSource->originalDataSource()->SetAnnotation(Attributes::FILENAME,
                                                    fileName.toLatin1().data());
    LoadDataReaction::dataSourceAdded(dataSource);
  } else if (info.completeSuffix().endsWith("ome.tif")) {
    auto pxm = tomviz::ActiveObjects::instance().proxyManager();
    vtkSmartPointer<vtkSMProxy> source;
    source.TakeReference(pxm->NewProxy("sources", "OMETIFFReader"));
    QString pname = vtkSMCoreUtilities::GetFileNameProperty(source);
    vtkSMStringVectorProperty *prop = vtkSMStringVectorProperty::SafeDownCast(source->GetProperty(pname.toUtf8().data()));
    pqSMAdaptor::setElementProperty(prop, fileName);
    source->UpdateVTKObjects();

    dataSource = createDataSource(source);
    // The dataSource may be NULL if the user cancelled the action.
    if (dataSource) {
      RecentFilesMenu::pushDataReader(dataSource, source);
    }
  } else {
    // Use ParaView's file load infrastructure.
    pqPipelineSource* reader = pqLoadDataReaction::loadData(fileNames);

    if (!reader) {
      return nullptr;
    }

    dataSource = createDataSource(reader->getProxy());
    // The dataSource may be NULL if the user cancelled the action.
    if (dataSource) {
      RecentFilesMenu::pushDataReader(dataSource, reader->getProxy());
    }
    vtkNew<vtkSMParaViewPipelineController> controller;
    controller->UnRegisterProxy(reader->getProxy());
  }

  return dataSource;
}

namespace {
bool hasData(vtkSMProxy* reader) {
  vtkSMSourceProxy* dataSource = vtkSMSourceProxy::SafeDownCast(reader);
  if (!dataSource) {
    return false;
  }

  dataSource->UpdatePipeline();
  vtkAlgorithm* vtkalgorithm =
    vtkAlgorithm::SafeDownCast(dataSource->GetClientSideObject());
  if (!vtkalgorithm) {
    return false;
  }

  // Create a clone and release the reader data.
  vtkImageData* data = vtkImageData::SafeDownCast(vtkalgorithm->GetOutputDataObject(0));
  if (!data) {
    return false;
  }

  int extent[6];
  data->GetExtent(extent);
  if (extent[0] > extent[1] || extent[2] > extent[3] || extent[4] > extent[5]) {
    return false;
  }

  vtkPointData* pd = data->GetPointData();
  if (!pd) {
    return false;
  }

  vtkDataArray* scalars = pd->GetScalars();
  if (!scalars || scalars->GetNumberOfTuples() == 0) {
    return false;
  }
  return true;
}
}

DataSource* LoadDataReaction::createDataSource(vtkSMProxy* reader)
{
  // Prompt user for reader configuration.
  pqProxyWidgetDialog dialog(reader);
  dialog.setObjectName("ConfigureReaderDialog");
  dialog.setWindowTitle("Configure Reader Parameters");
  if (dialog.hasVisibleWidgets() == false ||
      dialog.exec() == QDialog::Accepted) {
    DataSource* previousActiveDataSource =
      ActiveObjects::instance().activeDataSource();

    if (!hasData(reader)) {
      qCritical() << "Error: failed to load file!";
      return nullptr;
    }

    DataSource* dataSource =
      new DataSource(vtkSMSourceProxy::SafeDownCast(reader));
    // do whatever we need to do with a new data source.
    LoadDataReaction::dataSourceAdded(dataSource);
    if (!previousActiveDataSource) {
      pqRenderView* renderView =
        qobject_cast<pqRenderView*>(pqActiveObjects::instance().activeView());
      if (renderView) {
        tomviz::createCameraOrbit(dataSource->producer(),
                                  renderView->getRenderViewProxy());
      }
    }
    return dataSource;
  }
  return nullptr;
}

DataSource* LoadDataReaction::createDataSource(vtkImageData* imageData)
{
  auto pxm = tomviz::ActiveObjects::instance().proxyManager();
  vtkSmartPointer<vtkSMProxy> source;
  source.TakeReference(pxm->NewProxy("sources", "TrivialProducer"));
  auto tp = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject());
  tp->SetOutput(imageData);
  source->SetAnnotation("tomviz.Type", "DataSource");

  auto dataSource = new DataSource(vtkSMSourceProxy::SafeDownCast(source));
  return dataSource;
}

void LoadDataReaction::dataSourceAdded(DataSource* dataSource)
{
  bool oldMoveObjectsEnabled = ActiveObjects::instance().moveObjectsEnabled();
  ActiveObjects::instance().setMoveObjectsMode(false);
  ModuleManager::instance().addDataSource(dataSource);

  ActiveObjects::instance().createRenderViewIfNeeded();
  ActiveObjects::instance().setActiveViewToFirstRenderView();

  vtkSMViewProxy* view = ActiveObjects::instance().activeView();

  // Create an outline module for the source in the active view.
  if (Module* module = ModuleManager::instance().createAndAddModule(
        "Outline", dataSource, view)) {
    ActiveObjects::instance().setActiveModule(module);
  }
  if (Module* module = ModuleManager::instance().createAndAddModule(
        "Orthogonal Slice", dataSource, view)) {
    ActiveObjects::instance().setActiveModule(module);
  }
  ActiveObjects::instance().setMoveObjectsMode(oldMoveObjectsEnabled);
}

} // end of namespace tomviz
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CKinFunction.cpp,v $
   $Revision: 1.60 $
   $Name:  $
   $Author: shoops $
   $Date: 2006/04/27 01:28:26 $
   End CVS Header */

// Copyright  2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

/**
 * CKinFunction
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2002
 */

#undef yyFlexLexer
#define yyFlexLexer CKinFunctionFlexLexer

#include <sstream>

#include "copasi.h"
#include "mathematics.h"

#include "CKinFunctionFlexLexer.h"
#include "CKinFunction.h"
#include "utilities/CCopasiException.h"
#include "report/CCopasiContainer.h"
#include "report/CCopasiObject.h"
#include "utilities/utility.h"

CKinFunction::CKinFunction(const std::string & name,
                           const CCopasiContainer * pParent):
    CFunction(name, pParent, CFunction::UserDefined)
{
  CONSTRUCTOR_TRACE;
}

CKinFunction::CKinFunction(const CFunction & src,
                           CReadConfig * configBuffer,
                           const CCopasiContainer * pParent):
    CFunction(src, pParent)
{
  CONSTRUCTOR_TRACE;

  if (configBuffer)
    {
      unsigned C_INT32 i, Size;
      configBuffer->getVariable("Nodes", "C_INT32", &Size);
      mNodes.resize(Size);

      for (i = 0; i < Size; i++)
        {
          mNodes[i] = new CNodeK;
          mNodes[i]->load(*configBuffer);
        }

      createParameters();

      cleanupNodes();
    }

  //  compile();
}

CKinFunction::CKinFunction(const CKinFunction & src,
                           const CCopasiContainer * pParent):
    CFunction(src, pParent)
{
  CONSTRUCTOR_TRACE;
  compile();
}

CKinFunction::~CKinFunction()
{
  /*  int i;
    for (i=0; i<ObjList.size(); i++)
     ObjList[i] = NULL;
  */
  ObjList.clear();
  cleanup();
  DESTRUCTOR_TRACE;
}

void CKinFunction::cleanup()
{
  cleanupNodes();
}

// This is used when reading Gepasi Files
void CKinFunction::createParameters()
{
  CCopasiVectorN < CFunctionParameter > Substrates;
  CCopasiVectorN < CFunctionParameter > Products;
  CCopasiVectorN < CFunctionParameter > Modifiers;
  CCopasiVectorN < CFunctionParameter > Parameters;
  CCopasiVectorN < CFunctionParameter > Volumes;

  unsigned C_INT32 i, imax = mNodes.size();

  CFunctionParameter *pParameter;

  for (i = 0; i < imax; i++)
    {
      if (mNodes[i]->getType() == N_IDENTIFIER)
        {
          pParameter = new CFunctionParameter(mNodes[i]->getName());
          //          Parameter.setName(mNodes[i]->getObjectName());
          pParameter->setType(CFunctionParameter::FLOAT64);

          switch (mNodes[i]->getSubtype())
            {
            case N_SUBSTRATE:
              pParameter->setUsage(CFunctionParameter::SUBSTRATE);
              if (Substrates.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Substrates.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_PRODUCT:
              pParameter->setUsage(CFunctionParameter::PRODUCT);
              if (Products.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Products.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_MODIFIER:
              pParameter->setUsage(CFunctionParameter::MODIFIER);
              if (Modifiers.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Modifiers.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_KCONSTANT:
            case N_NOP:
              pParameter->setUsage(CFunctionParameter::PARAMETER);
              if (Parameters.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Parameters.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_VOLUME:
              pParameter->setUsage(CFunctionParameter::VOLUME);
              if (Volumes.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Volumes.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            default:
              pdelete(pParameter);
              fatalError();
            }
        }
    }

  getVariables().cleanup();

  imax = Substrates.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Substrates[i], true);
  Substrates.cleanup();

  imax = Products.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Products[i], true);
  Products.cleanup();

  imax = Modifiers.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Modifiers[i], true);
  Modifiers.cleanup();

  imax = Parameters.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Parameters[i], true);
  Parameters.cleanup();

  imax = Volumes.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Volumes[i], true);
  Volumes.cleanup();
}

std::vector< CNodeK * > & CKinFunction::getNodes() {return mNodes;}

void CKinFunction::cleanupNodes()
{
  unsigned C_INT32 i, imax = mNodes.size();

  for (i = 0; i < imax; i++)
    if (mNodes[i]) delete mNodes[i];

  mNodes.clear();
  return;
}

/*void CKinFunction::writeMathML(std::ostream & out) const
  {
    //if (!mNodes[0]->isLeftValid()) return;

    out << "<math>" << std::endl;
    //mNodes[0]->getLeft().writeMathML(out, 0);
    out << "</math>" << std::endl;
  }*/
<commit_msg>Fixed Bug 509. All invalid Gepasi identifiers are mapped to COPASI variables with a '_' prepended.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CKinFunction.cpp,v $
   $Revision: 1.61 $
   $Name:  $
   $Author: shoops $
   $Date: 2006/05/01 16:12:25 $
   End CVS Header */

// Copyright  2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

/**
 * CKinFunction
 *
 * Created for Copasi by Stefan Hoops
 * (C) Stefan Hoops 2002
 */

#undef yyFlexLexer
#define yyFlexLexer CKinFunctionFlexLexer

#include <sstream>

#include "copasi.h"
#include "mathematics.h"

#include "CKinFunctionFlexLexer.h"
#include "CKinFunction.h"
#include "utilities/CCopasiException.h"
#include "report/CCopasiContainer.h"
#include "report/CCopasiObject.h"
#include "utilities/utility.h"

CKinFunction::CKinFunction(const std::string & name,
                           const CCopasiContainer * pParent):
    CFunction(name, pParent, CFunction::UserDefined)
{
  CONSTRUCTOR_TRACE;
}

CKinFunction::CKinFunction(const CFunction & src,
                           CReadConfig * configBuffer,
                           const CCopasiContainer * pParent):
    CFunction(src, pParent)
{
  CONSTRUCTOR_TRACE;

  if (configBuffer)
    {
      unsigned C_INT32 i, Size;
      configBuffer->getVariable("Nodes", "C_INT32", &Size);
      mNodes.resize(Size);

      for (i = 0; i < Size; i++)
        {
          mNodes[i] = new CNodeK;
          mNodes[i]->load(*configBuffer);
        }

      createParameters();

      cleanupNodes();
    }

  //  compile();
}

CKinFunction::CKinFunction(const CKinFunction & src,
                           const CCopasiContainer * pParent):
    CFunction(src, pParent)
{
  CONSTRUCTOR_TRACE;
  compile();
}

CKinFunction::~CKinFunction()
{
  /*  int i;
    for (i=0; i<ObjList.size(); i++)
     ObjList[i] = NULL;
  */
  ObjList.clear();
  cleanup();
  DESTRUCTOR_TRACE;
}

void CKinFunction::cleanup()
{
  cleanupNodes();
}

// This is only used when reading Gepasi Files
void CKinFunction::createParameters()
{
  CCopasiVectorN < CFunctionParameter > Substrates;
  CCopasiVectorN < CFunctionParameter > Products;
  CCopasiVectorN < CFunctionParameter > Modifiers;
  CCopasiVectorN < CFunctionParameter > Parameters;
  CCopasiVectorN < CFunctionParameter > Volumes;

  unsigned C_INT32 i, imax = mNodes.size();

  CFunctionParameter *pParameter;

  for (i = 0; i < imax; i++)
    {
      if (mNodes[i]->getType() == N_IDENTIFIER)
        {
          // We need to check that we have no reserved name.
          const char *Reserved[] =
            {"pi", "exponentiale", "true", "false", "infinity",
             "PI", "EXPONENTIALE", "TRUE", "FALSE", "INFINITY"
            };

          std::string Name = mNodes[i]->getName();
          unsigned C_INT32 j, jmax = 10;
          for (j = 0; j < 10; j++)
            if (Name == Reserved[j]) break;

          if (j != jmax)
            {
              // It is save to prepend the identifyer with '_' since this is not allowed in
              // Gepasi but within COPASI.
              std::string OldName = Name;
              Name = "_" + Name;

              // We have to replace the corresponding CEvaluationNodes to reflect the change.
              std::vector< CEvaluationNode * >::iterator it = mpNodeList->begin();
              std::vector< CEvaluationNode * >::iterator end = mpNodeList->end();

              for (; it != end; ++it)
                if (((*it)->getType() & 0xFF000000) == CEvaluationNode::CONSTANT &&
                    (*it)->getData() == OldName)
                  (*it)->setData(Name);

              // The Infix has changed we need to update it.
              setInfix(mpRoot->getInfix());
            }

          pParameter = new CFunctionParameter(Name);
          pParameter->setType(CFunctionParameter::FLOAT64);

          switch (mNodes[i]->getSubtype())
            {
            case N_SUBSTRATE:
              pParameter->setUsage(CFunctionParameter::SUBSTRATE);
              if (Substrates.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Substrates.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_PRODUCT:
              pParameter->setUsage(CFunctionParameter::PRODUCT);
              if (Products.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Products.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_MODIFIER:
              pParameter->setUsage(CFunctionParameter::MODIFIER);
              if (Modifiers.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Modifiers.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_KCONSTANT:
            case N_NOP:
              pParameter->setUsage(CFunctionParameter::PARAMETER);
              if (Parameters.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Parameters.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            case N_VOLUME:
              pParameter->setUsage(CFunctionParameter::VOLUME);
              if (Volumes.getIndex(pParameter->getObjectName()) == C_INVALID_INDEX)
                Volumes.add(pParameter, false);
              else
                pdelete(pParameter);
              break;

            default:
              pdelete(pParameter);
              fatalError();
            }
        }
    }

  getVariables().cleanup();

  imax = Substrates.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Substrates[i], true);
  Substrates.cleanup();

  imax = Products.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Products[i], true);
  Products.cleanup();

  imax = Modifiers.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Modifiers[i], true);
  Modifiers.cleanup();

  imax = Parameters.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Parameters[i], true);
  Parameters.cleanup();

  imax = Volumes.size();
  for (i = 0; i < imax; i++)
    getVariables().add(Volumes[i], true);
  Volumes.cleanup();
}

std::vector< CNodeK * > & CKinFunction::getNodes() {return mNodes;}

void CKinFunction::cleanupNodes()
{
  unsigned C_INT32 i, imax = mNodes.size();

  for (i = 0; i < imax; i++)
    if (mNodes[i]) delete mNodes[i];

  mNodes.clear();
  return;
}

/*void CKinFunction::writeMathML(std::ostream & out) const
  {
    //if (!mNodes[0]->isLeftValid()) return;

    out << "<math>" << std::endl;
    //mNodes[0]->getLeft().writeMathML(out, 0);
    out << "</math>" << std::endl;
  }*/
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <istream>

// template <class charT, class traits = char_traits<charT> >
//   class basic_istream;

// basic_istream<charT,traits>& operator<<(basic_streambuf<charT,traits>* sb);

#include <istream>
#include <cassert>

template <class CharT>
class testbuf
    : public std::basic_streambuf<CharT>
{
    typedef std::basic_streambuf<CharT> base;
    std::basic_string<CharT> str_;
public:
    testbuf()
    {
    }
    testbuf(const std::basic_string<CharT>& str)
        : str_(str)
    {
        base::setg(const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data() + str_.size()));
    }

    std::basic_string<CharT> str() const
        {return std::basic_string<CharT>(base::pbase(), base::pptr());}

protected:

    virtual typename base::int_type
        overflow(typename base::int_type ch = base::traits_type::eof())
        {
            if (ch != base::traits_type::eof())
            {
                std::size_t n = str_.size();
                str_.push_back(static_cast<CharT>(ch));
                str_.resize(str_.capacity());
                base::setp(const_cast<CharT*>(str_.data()),
                           const_cast<CharT*>(str_.data() + str_.size()));
                base::pbump(n+1);
            }
            return ch;
        }
};

int main()
{
    {
        testbuf<char> sb("testing...");
        std::istream is(&sb);
        testbuf<char> sb2;
        is >> &sb2;
        assert(sb2.str() == "testing...");
        assert(is.gcount() == 10);
    }
}
<commit_msg>[libcxx] [test] Fix MSVC x64 truncation warning.<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <istream>

// template <class charT, class traits = char_traits<charT> >
//   class basic_istream;

// basic_istream<charT,traits>& operator<<(basic_streambuf<charT,traits>* sb);

#include <istream>
#include <cassert>

template <class CharT>
class testbuf
    : public std::basic_streambuf<CharT>
{
    typedef std::basic_streambuf<CharT> base;
    std::basic_string<CharT> str_;
public:
    testbuf()
    {
    }
    testbuf(const std::basic_string<CharT>& str)
        : str_(str)
    {
        base::setg(const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data() + str_.size()));
    }

    std::basic_string<CharT> str() const
        {return std::basic_string<CharT>(base::pbase(), base::pptr());}

protected:

    virtual typename base::int_type
        overflow(typename base::int_type ch = base::traits_type::eof())
        {
            if (ch != base::traits_type::eof())
            {
                std::size_t n = str_.size();
                str_.push_back(static_cast<CharT>(ch));
                str_.resize(str_.capacity());
                base::setp(const_cast<CharT*>(str_.data()),
                           const_cast<CharT*>(str_.data() + str_.size()));
                base::pbump(static_cast<int>(n+1));
            }
            return ch;
        }
};

int main()
{
    {
        testbuf<char> sb("testing...");
        std::istream is(&sb);
        testbuf<char> sb2;
        is >> &sb2;
        assert(sb2.str() == "testing...");
        assert(is.gcount() == 10);
    }
}
<|endoftext|>