<commit_before>#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "kernel.h"
#include <QDebug>
#include <iostream>
#include <fstream>

Kernel::Kernel(int argc, char** argv)
{
	/* default config */
	server_port = DEF_PORT;
	local_port = DEF_PORT;
	height = DEF_HEIGHT;
	width = DEF_WIDTH;
	fullscreen = false;
	mode = SINGLEPLAY;
	map_name = (char*)malloc(255);
	strcpy(map_name, "default_map");
    load_config();
	/* parse command line arguments */
	static const char *optString = "m:h:w:f:c:s";
	int opt = 0;
	opt = getopt(argc, argv, optString);
	while(opt != -1)
	{
		switch(opt) {
			case 'm':
				map_name = (char*)malloc(sizeof(optarg));
				strcpy(map_name, optarg);
				break;
			case 'h':
				height = atof(optarg);
				break;
			case 'w':
				width = atof(optarg);
				break;
			case 'f':
				fullscreen = atoi(optarg);
				break;
			case 'c':
				if (mode == SERVER)
				{
					printf("Warning: options -c and -s should not be used at one time\n");
				}
				mode = CLIENT;
				server_address = (char*)malloc(sizeof(optarg));
				strcpy(server_address, optarg);
				break;
			case 's':
				if (mode == CLIENT)
				{
					printf("Warning: options -c and -s should not be used at one time\n");
				}
				mode = SERVER;
				break;
		}
		opt = getopt(argc, argv, optString);
	}
	save_config();
	printf("Resolution set to %fx%f\n", width, height);
	if (fullscreen)
	{
		printf("Mode fullscreen\n");
	}
	else
	{
		printf("Mode windowed\n");
	}
	switch (mode)
	{
		case SINGLEPLAY:
			printf("Mode singleplay\n");
			break;
		case CLIENT:
			printf("Mode client, server address is %s\n", server_address);
			break;
		case SERVER:
			printf("Mode server\n");
			break;
	}
    fpc_info.fpc = 0;
    fpc_info.fpc_max = 0;
    fpc_info.fpc_min = 0;
    fpc_info.fpc_min -=1;
}

void Kernel::load_config()
{
	/* open and read config file */
	char option[255];
	char value[255];
	FILE *config_file;
	config_file = fopen(CONFIG_PATH, "r");
	if (config_file != NULL)
	{
		while(fscanf(config_file, "%s %s", option, value) != EOF)
		{
			if (!strcmp(option, "height"))
			{
				height = atof(value);
			}
			if (!strcmp(option, "width"))
			{
				width = atof(value);
			}
			if (!strcmp(option, "fullscreen"))
			{
				fullscreen = atoi(value);
			}
		}
		fclose(config_file);
	}
	else
	{
		printf("Warning: no config file found\n");
	}
}

void Kernel::save_config()
{
	/* write config to config file */
	FILE *config_file;
	config_file = fopen(CONFIG_PATH, "w");
	if (config_file != NULL)
	{
		fprintf(config_file, "%s %f\n", "width", width);
		fprintf(config_file, "%s %f\n", "height", height);
		fprintf(config_file, "%s %i\n", "fullscreen", fullscreen);
		fclose(config_file);
		printf("Config saved\n");
	}
	else
	{
		printf("Warning: can not save config\n");
	}
}

/* was not tested yet */
void Kernel::do_command(char* input)
{
    printf("kernel \x1b[31mDEBUG\x1b[0m input comand '%s'\n", input);
	char command[255];
	sscanf(input, "%s", command);
	if (!strcmp(command, "connect"))
	{
		mode = CLIENT;
		sscanf(input, "%s %s:%d", command, server_address, &server_port);
		/* ... */
	}
	if (!strcmp(command, "server"))
	{
		mode = SERVER;
		sscanf(input, "%s %d", command, &local_port);
		/* ... */
	}
	if (!strcmp(command, "fullscreen"))
	{
		fullscreen = false;
		/* ... */
		save_config();
	}
	if (!strcmp(command, "windowed"))
	{
		fullscreen = true;
		/* ... */
		save_config();
	}
    if (!strcmp(command, "fpc"))
    {
        print_fpc();
    }
  if (!strcmp(command, "loadmap"))
  {
		sscanf(input, "%s %s", command, map_name);
		load_map();
	}
}

void Kernel::load_map()
{
	printf("Loading map %s\n", map_name);
	SModel* model;
	/* erase all models from vector */
	printf("Erasing objects\n");
  while(!models.empty())
	{
        model = models.back();
        delete model->position;
				free(model);
        models.pop_back();
	}
    std::ifstream map_file;
    char map_path[255];
	map_path[0] = '\0';
	strcat(map_path, "res/maps/");
	strcat(map_path, map_name);
	strcat(map_path, ".map");
	printf("Map path is %s\n", map_path);
    map_file.open((char*)map_path);
    for(std::string str; std::getline(map_file, str); )
        {
         model = new SModel;

//        model->position->position.init(p0, p1, p2);
//        model->position->velocity.init(v0, v1, v2);
//        model->position->acceleration.init(a0, a1, a2);
//        model->position->angular_position.init(ap0, ap1, ap2);
//        model->position->angular_velocity.init(av0, av1, av2);
//        model->position->angular_acceleration.init(aa0, aa1, aa2);
//        models.push_back(model);
//        printf("Added object %d\n", id);
	}
	map_file.close();

}

void Kernel::print_fpc()
{
    qDebug() << "fpc now: " << fpc_info.fpc;
    qDebug() << "fpc max: " << fpc_info.fpc_max;
    qDebug() << "fpc min: " << fpc_info.fpc_min;
}

void Kernel::get_network(Network* _network)
{
	network = _network;
}
<commit_msg>parser fix<commit_after>#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "kernel.h"
#include <QDebug>
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

Kernel::Kernel(int argc, char** argv)
{
	/* default config */
	server_port = DEF_PORT;
	local_port = DEF_PORT;
	height = DEF_HEIGHT;
	width = DEF_WIDTH;
	fullscreen = false;
	mode = SINGLEPLAY;
	map_name = (char*)malloc(255);
	strcpy(map_name, "default_map");
    load_config();
	/* parse command line arguments */
	static const char *optString = "m:h:w:f:c:s";
	int opt = 0;
	opt = getopt(argc, argv, optString);
	while(opt != -1)
	{
		switch(opt) {
			case 'm':
				map_name = (char*)malloc(sizeof(optarg));
				strcpy(map_name, optarg);
				break;
			case 'h':
				height = atof(optarg);
				break;
			case 'w':
				width = atof(optarg);
				break;
			case 'f':
				fullscreen = atoi(optarg);
				break;
			case 'c':
				if (mode == SERVER)
				{
					printf("Warning: options -c and -s should not be used at one time\n");
				}
				mode = CLIENT;
				server_address = (char*)malloc(sizeof(optarg));
				strcpy(server_address, optarg);
				break;
			case 's':
				if (mode == CLIENT)
				{
					printf("Warning: options -c and -s should not be used at one time\n");
				}
				mode = SERVER;
				break;
		}
		opt = getopt(argc, argv, optString);
	}
	save_config();
	printf("Resolution set to %fx%f\n", width, height);
	if (fullscreen)
	{
		printf("Mode fullscreen\n");
	}
	else
	{
		printf("Mode windowed\n");
	}
	switch (mode)
	{
		case SINGLEPLAY:
			printf("Mode singleplay\n");
			break;
		case CLIENT:
			printf("Mode client, server address is %s\n", server_address);
			break;
		case SERVER:
			printf("Mode server\n");
			break;
	}
    fpc_info.fpc = 0;
    fpc_info.fpc_max = 0;
    fpc_info.fpc_min = 0;
    fpc_info.fpc_min -=1;
}

void Kernel::load_config()
{
	/* open and read config file */
	char option[255];
	char value[255];
	FILE *config_file;
	config_file = fopen(CONFIG_PATH, "r");
	if (config_file != NULL)
	{
		while(fscanf(config_file, "%s %s", option, value) != EOF)
		{
			if (!strcmp(option, "height"))
			{
				height = atof(value);
			}
			if (!strcmp(option, "width"))
			{
				width = atof(value);
			}
			if (!strcmp(option, "fullscreen"))
			{
				fullscreen = atoi(value);
			}
		}
		fclose(config_file);
	}
	else
	{
		printf("Warning: no config file found\n");
	}
}

void Kernel::save_config()
{
	/* write config to config file */
	FILE *config_file;
	config_file = fopen(CONFIG_PATH, "w");
	if (config_file != NULL)
	{
		fprintf(config_file, "%s %f\n", "width", width);
		fprintf(config_file, "%s %f\n", "height", height);
		fprintf(config_file, "%s %i\n", "fullscreen", fullscreen);
		fclose(config_file);
		printf("Config saved\n");
	}
	else
	{
		printf("Warning: can not save config\n");
	}
}

/* was not tested yet */
void Kernel::do_command(char* input)
{
    printf("kernel \x1b[31mDEBUG\x1b[0m input comand '%s'\n", input);
	char command[255];
	sscanf(input, "%s", command);
	if (!strcmp(command, "connect"))
	{
		mode = CLIENT;
		sscanf(input, "%s %s:%d", command, server_address, &server_port);
		/* ... */
	}
	if (!strcmp(command, "server"))
	{
		mode = SERVER;
		sscanf(input, "%s %d", command, &local_port);
		/* ... */
	}
	if (!strcmp(command, "fullscreen"))
	{
		fullscreen = false;
		/* ... */
		save_config();
	}
	if (!strcmp(command, "windowed"))
	{
		fullscreen = true;
		/* ... */
		save_config();
	}
    if (!strcmp(command, "fpc"))
    {
        print_fpc();
    }
  if (!strcmp(command, "loadmap"))
  {
		sscanf(input, "%s %s", command, map_name);
		load_map();
	}
}

void Kernel::load_map()
{
	printf("Loading map %s\n", map_name);
	SModel* model;
	/* erase all models from vector */
	printf("Erasing objects\n");
  while(!models.empty())
	{
        model = models.back();
        free(model);
        models.pop_back();
	}
    ifstream map_file;
    char map_path[255];
	map_path[0] = '\0';
	strcat(map_path, "res/maps/");
	strcat(map_path, map_name);
    strcat(map_path, ".map");
    map_file.open((char*)map_path);
    for(string str; getline(map_file, str); )
    {
        model = new SModel;
        istringstream str_stream(str);
        str_stream >> model->mesh_number;

        str_stream >> model->position.position.v[0];
        str_stream >> model->position.position.v[1];
        str_stream >> model->position.position.v[2];

        str_stream >> model->position.velocity.v[0];
        str_stream >> model->position.velocity.v[1];
        str_stream >> model->position.velocity.v[2];

        str_stream >> model->position.acceleration.v[0];
        str_stream >> model->position.acceleration.v[1];
        str_stream >> model->position.acceleration.v[2];

        str_stream >> model->position.angular_position.v[0];
        str_stream >> model->position.angular_position.v[1];
        str_stream >> model->position.angular_position.v[2];

        str_stream >> model->position.angular_velocity.v[0];
        str_stream >> model->position.angular_velocity.v[1];
        str_stream >> model->position.angular_velocity.v[2];

        str_stream >> model->position.angular_acceleration.v[0];
        str_stream >> model->position.angular_acceleration.v[1];
        str_stream >> model->position.angular_acceleration.v[2];

        models.push_back(model);
	}
	map_file.close();

}

void Kernel::print_fpc()
{
    qDebug() << "fpc now: " << fpc_info.fpc;
    qDebug() << "fpc max: " << fpc_info.fpc_max;
    qDebug() << "fpc min: " << fpc_info.fpc_min;
}

void Kernel::get_network(Network* _network)
{
	network = _network;
}
<|endoftext|>


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

// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code.  Currently this tests:
//  Flash
//  Real
//  QuickTime
//  Windows Media Player
//    -this includes both WMP plugins.  npdsplay.dll is the older one that
//     comes with XP.  np-mswmp.dll can be downloaded from Microsoft and
//     needs SP2 or Vista.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/plugin_download_helper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/capturing_net_log.h"
#include "net/base/cert_verifier.h"
#include "net/base/host_resolver.h"
#include "net/base/net_util.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_layer.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_status.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/plugins/npapi/plugin_constants_win.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/plugin_switches.h"

#if defined(OS_WIN)
#include "base/win/registry.h"
#endif

class PluginTest : public UITest {
 public:
  // Generate the URL for testing a particular test.
  // HTML for the tests is all located in test_directory\plugin\<testcase>
  // Set |mock_http| to true to use mock HTTP server.
  static GURL GetTestUrl(const std::string &test_case, bool mock_http) {
    static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin");
    if (mock_http) {
      FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case);
      return URLRequestMockHTTPJob::GetMockUrl(plugin_path);
    }

    FilePath path;
    PathService::Get(chrome::DIR_TEST_DATA, &path);
    path = path.Append(kPluginPath).AppendASCII(test_case);
    return net::FilePathToFileURL(path);
  }

 protected:
#if defined(OS_WIN)
  virtual void SetUp() {
    const testing::TestInfo* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
      // The installer adds our process names to the registry key below.  Since
      // the installer might not have run on this machine, add it manually.
      base::win::RegKey regkey;
      if (regkey.Open(HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
                      KEY_WRITE)) {
        regkey.CreateKey(L"CHROME.EXE", KEY_READ);
      }
    } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
      // When testing the old WMP plugin, we need to force Chrome to not load
      // the new plugin.
      launch_arguments_.AppendSwitch(switches::kUseOldWMPPlugin);
    } else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
      launch_arguments_.AppendSwitchASCII(switches::kTestSandbox,
                                          "security_tests.dll");
    }

    UITest::SetUp();
  }
#endif  // defined(OS_WIN)

  void TestPlugin(const std::string& test_case,
                  int timeout,
                  bool mock_http) {
    GURL url = GetTestUrl(test_case, mock_http);
    NavigateToURL(url);
    WaitForFinish(timeout, mock_http);
  }

  // Waits for the test case to finish.
  void WaitForFinish(const int wait_time, bool mock_http) {
    static const char kTestCompleteCookie[] = "status";
    static const char kTestCompleteSuccess[] = "OK";

    GURL url = GetTestUrl("done", mock_http);
    scoped_refptr<TabProxy> tab(GetActiveTab());

    const std::string result =
        WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time);
    ASSERT_EQ(kTestCompleteSuccess, result);
  }
};

TEST_F(PluginTest, Flash) {
  // Note: This does not work with the npwrapper on 64-bit Linux. Install the
  // native 64-bit Flash to run the test.
  // TODO(thestig) Update this list if we decide to only test against internal
  // Flash plugin in the future?
  std::string kFlashQuery =
#if defined(OS_WIN)
      "npswf32.dll"
#elif defined(OS_MACOSX)
      "Flash Player.plugin"
#elif defined(OS_POSIX)
      "libflashplayer.so"
#endif
      ;
  TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false);
}

class ClickToPlayPluginTest : public PluginTest {
 public:
  ClickToPlayPluginTest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ClickToPlayPluginTest, Flash) {
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS,
                                                CONTENT_SETTING_BLOCK));

  GURL url = GetTestUrl("flash-clicktoplay.html", true);
  NavigateToURL(url);

  scoped_refptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(tab->LoadBlockedPlugins());

  WaitForFinish(action_max_timeout_ms(), true);
}

TEST_F(ClickToPlayPluginTest, FlashDocument) {
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS,
                                                CONTENT_SETTING_BLOCK));

  scoped_refptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());
  GURL url = GetTestUrl("js-invoker.swf?callback=done", true);
  NavigateToURL(url);

  // Inject the callback function into the HTML page generated by the browser.
  ASSERT_TRUE(tab->ExecuteJavaScript("window.done = function() {"
                                     "  window.location = \"done.html\";"
                                     "}"));

  ASSERT_TRUE(tab->LoadBlockedPlugins());

  WaitForFinish(action_max_timeout_ms(), true);
}

#if defined(OS_WIN)
// Windows only test
TEST_F(PluginTest, DISABLED_FlashSecurity) {
  TestPlugin("flash.html", action_max_timeout_ms(), false);
}
#endif  // defined(OS_WIN)

#if defined(OS_WIN)
// TODO(port) Port the following tests to platforms that have the required
// plugins.
// Flaky: http://crbug.com/55915
TEST_F(PluginTest, FLAKY_Quicktime) {
  TestPlugin("quicktime.html", action_max_timeout_ms(), false);
}

// Disabled - http://crbug.com/44662
TEST_F(PluginTest, DISABLED_MediaPlayerNew) {
  TestPlugin("wmp_new.html", action_max_timeout_ms(), false);
}

// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
  TestPlugin("wmp_old.html", action_max_timeout_ms(), false);
}

// Disabled - http://crbug.com/44673
TEST_F(PluginTest, DISABLED_Real) {
  TestPlugin("real.html", action_max_timeout_ms(), false);
}

TEST_F(PluginTest, FlashOctetStream) {
  TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false);
}

#if defined(OS_WIN)
// http://crbug.com/53926
TEST_F(PluginTest, FLAKY_FlashLayoutWhilePainting) {
#else
TEST_F(PluginTest, FlashLayoutWhilePainting) {
#endif
  TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true);
}

// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
  TestPlugin("Java.html", action_max_timeout_ms(), false);
}

TEST_F(PluginTest, Silverlight) {
  TestPlugin("silverlight.html", action_max_timeout_ms(), false);
}

// This class provides functionality to test the plugin installer download
// file functionality.
class PluginInstallerDownloadTest
    : public PluginDownloadUrlHelper::DownloadDelegate,
      public testing::Test {
 public:
  // This class provides HTTP request context information for the downloads.
  class UploadRequestContext : public URLRequestContext {
   public:
    UploadRequestContext() {
      Initialize();
    }

    ~UploadRequestContext() {
      DVLOG(1) << __FUNCTION__;
      delete http_transaction_factory_;
      delete http_auth_handler_factory_;
      delete cert_verifier_;
      delete host_resolver_;
    }

    void Initialize() {
      host_resolver_ =
          net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism,
                                        NULL, NULL);
      cert_verifier_ = new net::CertVerifier;
      net::ProxyConfigService* proxy_config_service =
          net::ProxyService::CreateSystemProxyConfigService(NULL, NULL);
      DCHECK(proxy_config_service);

      const size_t kNetLogBound = 50u;
      net_log_.reset(new net::CapturingNetLog(kNetLogBound));

      proxy_service_ = net::ProxyService::CreateUsingSystemProxyResolver(
          proxy_config_service, 0, net_log_.get());
      DCHECK(proxy_service_);

      ssl_config_service_ = new net::SSLConfigServiceDefaults;
      http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault(
          host_resolver_);
      http_transaction_factory_ = new net::HttpCache(
          net::HttpNetworkLayer::CreateFactory(host_resolver_,
                                               cert_verifier_,
                                               NULL /* dnsrr_resolver */,
                                               NULL /* dns_cert_checker */,
                                               NULL /* ssl_host_info_factory */,
                                               proxy_service_,
                                               ssl_config_service_,
                                               http_auth_handler_factory_,
                                               network_delegate_,
                                               NULL),
          net::HttpCache::DefaultBackend::InMemory(0));
    }

   private:
    scoped_ptr<net::NetLog> net_log_;
    scoped_ptr<net::URLSecurityManager> url_security_manager_;
  };

  PluginInstallerDownloadTest()
      : success_(false),
        download_helper_(NULL) {}
  ~PluginInstallerDownloadTest() {}

  void Start() {
    initial_download_path_ = PluginTest::GetTestUrl("flash.html", false);
    download_helper_ = new PluginDownloadUrlHelper(
        initial_download_path_.spec(), base::GetCurrentProcId(), NULL,
        static_cast<PluginDownloadUrlHelper::DownloadDelegate*>(this));
    download_helper_->InitiateDownload(new UploadRequestContext);

    MessageLoop::current()->PostDelayedTask(
        FROM_HERE, new MessageLoop::QuitTask,
        TestTimeouts::action_max_timeout_ms());
  }

  virtual void OnDownloadCompleted(const FilePath& download_path,
                                   bool success) {
    success_ = success;
    final_download_path_ = download_path;
    MessageLoop::current()->Quit();
    download_helper_ = NULL;
  }

  FilePath final_download_path() const {
    return final_download_path_;
  }

  FilePath initial_download_path() const {
    return final_download_path_;
  }

  bool success() const {
    return success_;
  }

 private:
  FilePath final_download_path_;
  PluginDownloadUrlHelper* download_helper_;
  bool success_;
  GURL initial_download_path_;
};

// This test validates that the plugin downloader downloads the specified file
// to a temporary path with the same file name.
TEST_F(PluginInstallerDownloadTest, PluginInstallerDownloadPathTest) {
  MessageLoop loop(MessageLoop::TYPE_IO);
  Start();
  loop.Run();

  EXPECT_TRUE(success());
  EXPECT_TRUE(initial_download_path().BaseName().value() ==
              final_download_path().BaseName().value());
}
#endif  // defined(OS_WIN)
<commit_msg>Disable plugin tests on mac.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code.  Currently this tests:
//  Flash
//  Real
//  QuickTime
//  Windows Media Player
//    -this includes both WMP plugins.  npdsplay.dll is the older one that
//     comes with XP.  np-mswmp.dll can be downloaded from Microsoft and
//     needs SP2 or Vista.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include <string>

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/plugin_download_helper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/capturing_net_log.h"
#include "net/base/cert_verifier.h"
#include "net/base/host_resolver.h"
#include "net/base/net_util.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_layer.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_status.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/plugins/npapi/plugin_constants_win.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/plugin_switches.h"

#if defined(OS_WIN)
#include "base/win/registry.h"
#endif

class PluginTest : public UITest {
 public:
  // Generate the URL for testing a particular test.
  // HTML for the tests is all located in test_directory\plugin\<testcase>
  // Set |mock_http| to true to use mock HTTP server.
  static GURL GetTestUrl(const std::string &test_case, bool mock_http) {
    static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin");
    if (mock_http) {
      FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case);
      return URLRequestMockHTTPJob::GetMockUrl(plugin_path);
    }

    FilePath path;
    PathService::Get(chrome::DIR_TEST_DATA, &path);
    path = path.Append(kPluginPath).AppendASCII(test_case);
    return net::FilePathToFileURL(path);
  }

 protected:
#if defined(OS_WIN)
  virtual void SetUp() {
    const testing::TestInfo* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
      // The installer adds our process names to the registry key below.  Since
      // the installer might not have run on this machine, add it manually.
      base::win::RegKey regkey;
      if (regkey.Open(HKEY_LOCAL_MACHINE,
                      L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
                      KEY_WRITE)) {
        regkey.CreateKey(L"CHROME.EXE", KEY_READ);
      }
    } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
      // When testing the old WMP plugin, we need to force Chrome to not load
      // the new plugin.
      launch_arguments_.AppendSwitch(switches::kUseOldWMPPlugin);
    } else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
      launch_arguments_.AppendSwitchASCII(switches::kTestSandbox,
                                          "security_tests.dll");
    }

    UITest::SetUp();
  }
#endif  // defined(OS_WIN)

  void TestPlugin(const std::string& test_case,
                  int timeout,
                  bool mock_http) {
    GURL url = GetTestUrl(test_case, mock_http);
    NavigateToURL(url);
    WaitForFinish(timeout, mock_http);
  }

  // Waits for the test case to finish.
  void WaitForFinish(const int wait_time, bool mock_http) {
    static const char kTestCompleteCookie[] = "status";
    static const char kTestCompleteSuccess[] = "OK";

    GURL url = GetTestUrl("done", mock_http);
    scoped_refptr<TabProxy> tab(GetActiveTab());

    const std::string result =
        WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time);
    ASSERT_EQ(kTestCompleteSuccess, result);
  }
};

// http://crbug.com/68303
#if defined(OS_MACOSX)
TEST_F(PluginTest, DISABLED_Flash) {
#else
TEST_F(PluginTest, Flash) {
#endif
  // Note: This does not work with the npwrapper on 64-bit Linux. Install the
  // native 64-bit Flash to run the test.
  // TODO(thestig) Update this list if we decide to only test against internal
  // Flash plugin in the future?
  std::string kFlashQuery =
#if defined(OS_WIN)
      "npswf32.dll"
#elif defined(OS_MACOSX)
      "Flash Player.plugin"
#elif defined(OS_POSIX)
      "libflashplayer.so"
#endif
      ;
  TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false);
}

class ClickToPlayPluginTest : public PluginTest {
 public:
  ClickToPlayPluginTest() {
    dom_automation_enabled_ = true;
  }
};

// http://crbug.com/68303
#if defined(OS_MACOSX)
TEST_F(ClickToPlayPluginTest, DISABLED_Flash) {
#else
TEST_F(ClickToPlayPluginTest, Flash) {
#endif
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS,
                                                CONTENT_SETTING_BLOCK));

  GURL url = GetTestUrl("flash-clicktoplay.html", true);
  NavigateToURL(url);

  scoped_refptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());

  ASSERT_TRUE(tab->LoadBlockedPlugins());

  WaitForFinish(action_max_timeout_ms(), true);
}

// http://crbug.com/68303
#if defined(OS_MACOSX)
TEST_F(ClickToPlayPluginTest, DISABLED_FlashDocument) {
#else
TEST_F(ClickToPlayPluginTest, FlashDocument) {
#endif
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS,
                                                CONTENT_SETTING_BLOCK));

  scoped_refptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());
  GURL url = GetTestUrl("js-invoker.swf?callback=done", true);
  NavigateToURL(url);

  // Inject the callback function into the HTML page generated by the browser.
  ASSERT_TRUE(tab->ExecuteJavaScript("window.done = function() {"
                                     "  window.location = \"done.html\";"
                                     "}"));

  ASSERT_TRUE(tab->LoadBlockedPlugins());

  WaitForFinish(action_max_timeout_ms(), true);
}

#if defined(OS_WIN)
// Windows only test
TEST_F(PluginTest, DISABLED_FlashSecurity) {
  TestPlugin("flash.html", action_max_timeout_ms(), false);
}
#endif  // defined(OS_WIN)

#if defined(OS_WIN)
// TODO(port) Port the following tests to platforms that have the required
// plugins.
// Flaky: http://crbug.com/55915
TEST_F(PluginTest, FLAKY_Quicktime) {
  TestPlugin("quicktime.html", action_max_timeout_ms(), false);
}

// Disabled - http://crbug.com/44662
TEST_F(PluginTest, DISABLED_MediaPlayerNew) {
  TestPlugin("wmp_new.html", action_max_timeout_ms(), false);
}

// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
  TestPlugin("wmp_old.html", action_max_timeout_ms(), false);
}

// Disabled - http://crbug.com/44673
TEST_F(PluginTest, DISABLED_Real) {
  TestPlugin("real.html", action_max_timeout_ms(), false);
}

TEST_F(PluginTest, FlashOctetStream) {
  TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false);
}

#if defined(OS_WIN)
// http://crbug.com/53926
TEST_F(PluginTest, FLAKY_FlashLayoutWhilePainting) {
#else
TEST_F(PluginTest, FlashLayoutWhilePainting) {
#endif
  TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true);
}

// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
  TestPlugin("Java.html", action_max_timeout_ms(), false);
}

TEST_F(PluginTest, Silverlight) {
  TestPlugin("silverlight.html", action_max_timeout_ms(), false);
}

// This class provides functionality to test the plugin installer download
// file functionality.
class PluginInstallerDownloadTest
    : public PluginDownloadUrlHelper::DownloadDelegate,
      public testing::Test {
 public:
  // This class provides HTTP request context information for the downloads.
  class UploadRequestContext : public URLRequestContext {
   public:
    UploadRequestContext() {
      Initialize();
    }

    ~UploadRequestContext() {
      DVLOG(1) << __FUNCTION__;
      delete http_transaction_factory_;
      delete http_auth_handler_factory_;
      delete cert_verifier_;
      delete host_resolver_;
    }

    void Initialize() {
      host_resolver_ =
          net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism,
                                        NULL, NULL);
      cert_verifier_ = new net::CertVerifier;
      net::ProxyConfigService* proxy_config_service =
          net::ProxyService::CreateSystemProxyConfigService(NULL, NULL);
      DCHECK(proxy_config_service);

      const size_t kNetLogBound = 50u;
      net_log_.reset(new net::CapturingNetLog(kNetLogBound));

      proxy_service_ = net::ProxyService::CreateUsingSystemProxyResolver(
          proxy_config_service, 0, net_log_.get());
      DCHECK(proxy_service_);

      ssl_config_service_ = new net::SSLConfigServiceDefaults;
      http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault(
          host_resolver_);
      http_transaction_factory_ = new net::HttpCache(
          net::HttpNetworkLayer::CreateFactory(host_resolver_,
                                               cert_verifier_,
                                               NULL /* dnsrr_resolver */,
                                               NULL /* dns_cert_checker */,
                                               NULL /* ssl_host_info_factory */,
                                               proxy_service_,
                                               ssl_config_service_,
                                               http_auth_handler_factory_,
                                               network_delegate_,
                                               NULL),
          net::HttpCache::DefaultBackend::InMemory(0));
    }

   private:
    scoped_ptr<net::NetLog> net_log_;
    scoped_ptr<net::URLSecurityManager> url_security_manager_;
  };

  PluginInstallerDownloadTest()
      : success_(false),
        download_helper_(NULL) {}
  ~PluginInstallerDownloadTest() {}

  void Start() {
    initial_download_path_ = PluginTest::GetTestUrl("flash.html", false);
    download_helper_ = new PluginDownloadUrlHelper(
        initial_download_path_.spec(), base::GetCurrentProcId(), NULL,
        static_cast<PluginDownloadUrlHelper::DownloadDelegate*>(this));
    download_helper_->InitiateDownload(new UploadRequestContext);

    MessageLoop::current()->PostDelayedTask(
        FROM_HERE, new MessageLoop::QuitTask,
        TestTimeouts::action_max_timeout_ms());
  }

  virtual void OnDownloadCompleted(const FilePath& download_path,
                                   bool success) {
    success_ = success;
    final_download_path_ = download_path;
    MessageLoop::current()->Quit();
    download_helper_ = NULL;
  }

  FilePath final_download_path() const {
    return final_download_path_;
  }

  FilePath initial_download_path() const {
    return final_download_path_;
  }

  bool success() const {
    return success_;
  }

 private:
  FilePath final_download_path_;
  PluginDownloadUrlHelper* download_helper_;
  bool success_;
  GURL initial_download_path_;
};

// This test validates that the plugin downloader downloads the specified file
// to a temporary path with the same file name.
TEST_F(PluginInstallerDownloadTest, PluginInstallerDownloadPathTest) {
  MessageLoop loop(MessageLoop::TYPE_IO);
  Start();
  loop.Run();

  EXPECT_TRUE(success());
  EXPECT_TRUE(initial_download_path().BaseName().value() ==
              final_download_path().BaseName().value());
}
#endif  // defined(OS_WIN)
<|endoftext|>


<commit_before>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* 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 "stdafx.h"
#include "starbuck.h"
#include "BuildServerManager.h"

using namespace BlackBerry::Starbuck;

const int Starbuck::PROGRESS_BAR_HEIGHT = 23;

Starbuck::Starbuck(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags)
{
    init();
}

Starbuck::~Starbuck()
{
    if (_config != NULL)
    delete _config;

    if ( progressBar != NULL )
    delete progressBar;

    if ( webViewInternal != NULL )
    delete webViewInternal;
}

void Starbuck::init(void)
{
    _config = ConfigData::getInstance();
    setAttribute(Qt::WA_DeleteOnClose);

    webViewInternal = new QtStageWebView;
	webViewInternal->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
	webViewInternal->settings()->enablePersistentStorage(_config->localStoragePath());
    webViewInternal->settings()->setOfflineStorageDefaultQuota(512000000);
    webViewInternal->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
    webViewInternal->settings()->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, true);
    webViewInternal->settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled, true);
    webViewInternal->settings()->setAttribute(QWebSettings::WebGLEnabled, true);

    //Progress bar-------------------------
    progressBar = new QProgressBar(webViewInternal);
    progressBar->setObjectName(QString::fromUtf8("progressBar"));
    //When the loading of a new page has started, show and reset the progress bar
    connect(webViewInternal, SIGNAL(loadStarted()), progressBar, SLOT( show() ));
    connect(webViewInternal, SIGNAL(loadStarted()), progressBar, SLOT( reset()));
    //Increment the progress bar as the page loads
    connect(webViewInternal, SIGNAL(loadProgress(int)), progressBar, SLOT(setValue(int)));
    //When page is finished loading, hide the progress bar
    connect(webViewInternal, SIGNAL(loadFinished(bool)), progressBar, SLOT( hide() ));
    //--------------------------------------
    // init window

    QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
    QSize size = _config->windowSize();
    resize(size);

    if (_config->windowState() == 1)
        setWindowState(Qt::WindowMaximized);

    //Set geometry for progressbar
    progressBar->setGeometry(QRect(0, (size.height() - PROGRESS_BAR_HEIGHT), size.width(), PROGRESS_BAR_HEIGHT));

    move(_config->windowPosition());

    webViewInternal->load(QUrl(_config->toolingContent()));

    setCentralWidget(webViewInternal);

    //register webview
    connect(webViewInternal->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(registerAPIs()));

    //stagewebview interfaces
    m_pStageViewHandler = new StageViewMsgHandler(this);
    m_pStageViewHandler->Register(webViewInternal);

    //start build server
    connect(BuildServerManager::getInstance(), SIGNAL(findUsablePort(int)), m_pStageViewHandler, SLOT(setServerPort(int)));

    QFile cmd(_config->buildServiceCommand());
    if (cmd.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&cmd);
        m_pStageViewHandler->setServerPort(BuildServerManager::getInstance()->start(in.readLine(), _config->buildServicePort()));
        cmd.close();
    }
    else
    {
        qDebug() << "Can not open file:" << cmd.fileName() << "Error:" << cmd.error();
        cmd.close();
    }

}

void Starbuck::closeEvent(QCloseEvent *event)
{
    _config->windowPosition(pos());
    _config->windowSize(size());
    _config->windowState((this->windowState() == Qt::WindowMaximized) ? 1 : 0);
    _config->writeSettings();
    event->accept();
    BuildServerManager::getInstance()->stop();
}

void Starbuck::registerAPIs()
{
    //register StageWebViewMsgHandler as JS object named stagewebview
    QWebFrame* frame = webViewInternal->page()->mainFrame();
    frame->addToJavaScriptWindowObject(QString("stagewebview"), m_pStageViewHandler);
}

void Starbuck::resizeEvent(QResizeEvent * e )
{
	progressBar->setGeometry(QRect(0, (e->size().height() - PROGRESS_BAR_HEIGHT), e->size().width(), PROGRESS_BAR_HEIGHT));
    e->accept();
}
<commit_msg>Only enable WebGL and hardware accelerated composting on Qt 4.8<commit_after>/*
* Copyright 2010-2011 Research In Motion Limited.
*
* 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 "stdafx.h"
#include "starbuck.h"
#include "BuildServerManager.h"

using namespace BlackBerry::Starbuck;

const int Starbuck::PROGRESS_BAR_HEIGHT = 23;

Starbuck::Starbuck(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags)
{
    init();
}

Starbuck::~Starbuck()
{
    if (_config != NULL)
    delete _config;

    if ( progressBar != NULL )
    delete progressBar;

    if ( webViewInternal != NULL )
    delete webViewInternal;
}

void Starbuck::init(void)
{
    _config = ConfigData::getInstance();
    setAttribute(Qt::WA_DeleteOnClose);

    webViewInternal = new QtStageWebView;
	webViewInternal->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
	webViewInternal->settings()->enablePersistentStorage(_config->localStoragePath());
    webViewInternal->settings()->setOfflineStorageDefaultQuota(512000000);
    webViewInternal->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
    webViewInternal->settings()->setAttribute(QWebSettings::LocalContentCanAccessFileUrls, true);
#if QT_VERSION >= 0x040800
    webViewInternal->settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled, true);
    webViewInternal->settings()->setAttribute(QWebSettings::WebGLEnabled, true);
#endif

    //Progress bar-------------------------
    progressBar = new QProgressBar(webViewInternal);
    progressBar->setObjectName(QString::fromUtf8("progressBar"));
    //When the loading of a new page has started, show and reset the progress bar
    connect(webViewInternal, SIGNAL(loadStarted()), progressBar, SLOT( show() ));
    connect(webViewInternal, SIGNAL(loadStarted()), progressBar, SLOT( reset()));
    //Increment the progress bar as the page loads
    connect(webViewInternal, SIGNAL(loadProgress(int)), progressBar, SLOT(setValue(int)));
    //When page is finished loading, hide the progress bar
    connect(webViewInternal, SIGNAL(loadFinished(bool)), progressBar, SLOT( hide() ));
    //--------------------------------------
    // init window

    QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
    QSize size = _config->windowSize();
    resize(size);

    if (_config->windowState() == 1)
        setWindowState(Qt::WindowMaximized);

    //Set geometry for progressbar
    progressBar->setGeometry(QRect(0, (size.height() - PROGRESS_BAR_HEIGHT), size.width(), PROGRESS_BAR_HEIGHT));

    move(_config->windowPosition());

    webViewInternal->load(QUrl(_config->toolingContent()));

    setCentralWidget(webViewInternal);

    //register webview
    connect(webViewInternal->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(registerAPIs()));

    //stagewebview interfaces
    m_pStageViewHandler = new StageViewMsgHandler(this);
    m_pStageViewHandler->Register(webViewInternal);

    //start build server
    connect(BuildServerManager::getInstance(), SIGNAL(findUsablePort(int)), m_pStageViewHandler, SLOT(setServerPort(int)));

    QFile cmd(_config->buildServiceCommand());
    if (cmd.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&cmd);
        m_pStageViewHandler->setServerPort(BuildServerManager::getInstance()->start(in.readLine(), _config->buildServicePort()));
        cmd.close();
    }
    else
    {
        qDebug() << "Can not open file:" << cmd.fileName() << "Error:" << cmd.error();
        cmd.close();
    }

}

void Starbuck::closeEvent(QCloseEvent *event)
{
    _config->windowPosition(pos());
    _config->windowSize(size());
    _config->windowState((this->windowState() == Qt::WindowMaximized) ? 1 : 0);
    _config->writeSettings();
    event->accept();
    BuildServerManager::getInstance()->stop();
}

void Starbuck::registerAPIs()
{
    //register StageWebViewMsgHandler as JS object named stagewebview
    QWebFrame* frame = webViewInternal->page()->mainFrame();
    frame->addToJavaScriptWindowObject(QString("stagewebview"), m_pStageViewHandler);
}

void Starbuck::resizeEvent(QResizeEvent * e )
{
	progressBar->setGeometry(QRect(0, (e->size().height() - PROGRESS_BAR_HEIGHT), e->size().width(), PROGRESS_BAR_HEIGHT));
    e->accept();
}
<|endoftext|>


<commit_before>
/**************************************************************************
 * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/******************************************************************
 *    Produde digits from hits
 *       digits is TObject and includes
 *	We are writing array if C & A  TDC
 *	C & A  ADC (will need for slow simulation)
 *	TOF first particle C & A
 *	mean time and time difference (vertex position)
 *
 *      Alla.Maevskaya@cern.ch
 ****************************************************************/

#include <TArrayI.h>
#include <TFile.h>
#include <TGraph.h>
#include <TH1F.h>
#include <TMath.h>
#include <TRandom.h>
#include <TTree.h>

#include "AliLog.h"
#include "AliT0Digitizer.h"
#include "AliT0.h"
#include "AliT0hit.h"
#include "AliT0digit.h"
#include "AliRunDigitizer.h"
#include "AliRun.h"
#include <AliLoader.h>
#include <AliRunLoader.h>
#include <stdlib.h>
#include "AliT0Parameters.h"

ClassImp(AliT0Digitizer)

//___________________________________________
  AliT0Digitizer::AliT0Digitizer()  :AliDigitizer(),
				     fT0(0),
				     fHits(0),
				     fdigits(0),
				     ftimeCFD(new TArrayI(24)),
				     ftimeLED (new TArrayI(24)),
				     fADC(new TArrayI(24)),
				     fADC0 (new TArrayI(24)),
				     fSumMult(0),
				     fAmpLED(0),
                                     fAmpQTC(0),
				     fParam(0)

{
// Default ctor - don't use it
  ;
}

//___________________________________________
AliT0Digitizer::AliT0Digitizer(AliRunDigitizer* manager)
  :AliDigitizer(manager),
   fT0(0),
   fHits(0),
   fdigits(0),
   ftimeCFD(new TArrayI(24)),
   ftimeLED (new TArrayI(24)),
   fADC(new TArrayI(24)),
   fADC0 (new TArrayI(24)),
   fSumMult(0),
   fAmpLED(0),
   fAmpQTC(0),
   fParam(0)
{
// ctor which should be used

  AliDebug(1,"processed");
  fParam = AliT0Parameters::Instance();
  fParam->Init();

  for (Int_t i=0; i<24; i++){
    TGraph* gr = fParam ->GetAmpLED(i);
    Int_t np = gr->GetN();
    Double_t *x = gr->GetX();
    Double_t *y = gr->GetY();

    Double_t *x1 = new Double_t[np];
    Double_t *y1 = new Double_t[np];
    for (Int_t ii=0; ii<np; ii++) {
      y1[ii]=y[np-ii-1];
      x1[ii]=x[np-ii-1];
    }

    TGraph *grInverse = new TGraph(np,y1,x1);
    fAmpLED.AddAtAndExpand(grInverse,i);
  }
  for (Int_t i=0; i<24; i++){
    TGraph* grq = fParam ->GetQTC(i);
    Int_t npq = grq->GetN();
    Double_t *xq = grq->GetX();
    Double_t *yq = grq->GetY();
    Double_t *x1q = new Double_t[npq];
    Double_t *y1q = new Double_t[npq];
    for (Int_t ii=1; ii<npq; ii++) {
      y1q[ii]=yq[ii-1];
      x1q[ii]=xq[ii-1];
    }
  TGraph *grInverseQTC = new TGraph(npq,y1q,x1q);
  fAmpQTC.AddAtAndExpand(grInverseQTC,i);
  }
}

//------------------------------------------------------------------------
AliT0Digitizer::~AliT0Digitizer()
{
// Destructor

  AliDebug(1,"T0");

  delete ftimeCFD;
  delete fADC;
  delete ftimeLED;
  delete  fADC0;
  //  delete fAmpLED;
}

//------------------------------------------------------------------------
Bool_t AliT0Digitizer::Init()
{
// Initialization
  AliDebug(1," Init");
 return kTRUE;
}

//---------------------------------------------------------------------
void AliT0Digitizer::Exec(Option_t* /*option*/)
{

  /*
    Produde digits from hits
        digits is TObject and includes
	We are writing array if C & A  TDC
	C & A  ADC (will need for slow simulation)
	TOF first particle C & A
	mean time and time difference (vertex position)

  */

  //output loader
  AliRunLoader *outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
  AliLoader * pOutStartLoader = outRL->GetLoader("T0Loader");

  AliDebug(1,"start...");
  //input loader
  //
  // From hits to digits
  //
  Int_t hit, nhits;
  Int_t countE[24];
  Int_t volume, pmt, trCFD, trLED;
  Float_t sl, qt;
  Int_t  bestATDC=0;
  Int_t  bestCTDC=0;
  Float_t qtCh=0;
  Float_t time[24], besttime[24], timeGaus[24] ;
  //Q->T-> coefficients !!!! should be asked!!!
  Float_t timeDelayCFD[24];
  Int_t threshold =50; //photoelectrons
  Float_t zdetA, zdetC;
  Int_t sumMultCoeff = 100;
  Int_t refpoint=0;

  Int_t ph2Mip = fParam->GetPh2Mip();
  Float_t channelWidth = fParam->GetChannelWidth() ;
  Float_t delayVertex = fParam->GetTimeDelayTVD();

  zdetC = TMath::Abs(fParam->GetZPosition("T0/C/PMT1"));
  zdetA  = TMath::Abs(fParam->GetZPosition("T0/A/PMT15"));

  //  printf(" !!!!!Z det A = %f C = % f",zdetA,zdetC);
  AliT0hit  *startHit;
  TBranch *brHits=0;

  Int_t nFiles=fManager->GetNinputs();
  for (Int_t inputFile=0; inputFile<nFiles;  inputFile++) {
    if (inputFile < nFiles-1) {
      AliWarning(Form("ignoring input stream %d", inputFile));
      continue;

    }

    Float_t besttimeC=99999.;
    Float_t besttimeA=99999.;
    Int_t pmtBestC=99999;
    Int_t pmtBestA=99999;
    Int_t timeDiff=99999, meanTime=99999;
    Int_t sumMult =0;   fSumMult=0;
    bestATDC = 99999;  bestCTDC = 99999;

    ftimeCFD -> Reset();
    fADC -> Reset();
    fADC0 -> Reset();
    ftimeLED ->Reset();
    for (Int_t i0=0; i0<24; i0++)
      {
	time[i0]=besttime[i0]=timeGaus[i0]=999999; countE[i0]=0;
      }
    AliRunLoader * inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
    AliLoader * pInStartLoader = inRL->GetLoader("T0Loader");
    if (!inRL->GetAliRun()) inRL->LoadgAlice();
    fT0  = (AliT0*)inRL ->GetAliRun()->GetDetector("T0");

       //read Hits
    pInStartLoader->LoadHits("READ");//probably it is necessary to load them before
    fHits = fT0->Hits ();
    TTree *th = pInStartLoader->TreeH();
    brHits = th->GetBranch("T0");
    if (brHits) {
      fT0->SetHitsAddressBranch(brHits);
    }else{
      AliWarning("Branch T0 hit not found for this event");
      // fT0->AddDigit(bestATDC,bestCTDC,meanTime,timeDiff,fSumMult, refpoint,
      //	       ftimeCFD,fADC0,ftimeLED,fADC);
      continue;
    }
    Int_t ntracks    = (Int_t) th->GetEntries();

    if (ntracks<=0) return;
    // Start loop on tracks in the hits containers
    for (Int_t track=0; track<ntracks;track++) {
      brHits->GetEntry(track);
      nhits = fHits->GetEntriesFast();
      for (hit=0;hit<nhits;hit++)
	{
	  startHit   = (AliT0hit*) fHits->UncheckedAt(hit);
	  if (!startHit) {
 	    AliError("The unchecked hit doesn't exist");
	    break;
	  }
	  pmt=startHit->Pmt();
	  Int_t numpmt=pmt-1;
	  Double_t e=startHit->Etot();
	  volume = startHit->Volume();

	  if(e>0 ) {
	    countE[numpmt]++;
	    besttime[numpmt] = startHit->Time();
	    if(besttime[numpmt]<time[numpmt])
	      {
		time[numpmt]=besttime[numpmt];
	      }
	  } //photoelectron accept
	} //hits loop
    } //track loop

    //spread time A&C by 25ps   && besttime
    Float_t c = 0.0299792; // cm/ps

    Float_t koef=(zdetA-zdetC)/c; //correction position difference by cable
    for (Int_t ipmt=0; ipmt<12; ipmt++){
      if(countE[ipmt] > threshold) {
	timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25)+koef;
	if(timeGaus[ipmt]<besttimeC){
	  besttimeC=timeGaus[ipmt]; //timeC
	  pmtBestC=ipmt;}
      }
    }
    for ( Int_t ipmt=12; ipmt<24; ipmt++){
      if(countE[ipmt] > threshold) {
	timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
	if(timeGaus[ipmt]<besttimeA) {
	  besttimeA=timeGaus[ipmt]; //timeA
	  pmtBestA=ipmt;}
      }
    }

    timeDelayCFD[0] = fParam->GetTimeDelayCFD(0);

    for (Int_t i=0; i<24; i++)
      {
       	Float_t  al = countE[i];
	if (al>threshold && timeGaus[i]<50000 ) {
	  //fill ADC
	  // QTC procedure:
	  // phe -> mV 0.3; 1MIP ->500phe -> ln (amp (mV)) = 5;
	  // max 200ns, HIJING  mean 50000phe -> 15000mv -> ln = 15 (s zapasom)
	  // channel 25ps
	  qt= al/ph2Mip;  // 50mv/Mip amp in mV
	  // before will we have calibration for high multiplicity
	  if (qt > 115.) qt =115.; //must be fix!!!
	  //  fill TDC
	  timeDelayCFD[i] = fParam->GetTimeDelayCFD(i);
 	  trCFD = Int_t (timeGaus[i]/channelWidth + timeDelayCFD[i]);

	  TGraph* gr = ((TGraph*)fAmpLED.At(i));
	  sl = gr->Eval(qt);

	  TGraph* gr1 = ((TGraph*)fAmpQTC.At(i));
	  qtCh = gr1->Eval(qt);
	  fADC0->AddAt(0,i);
	  fADC->AddAt(qtCh,i);
	  //	  sumMult += Int_t ((al*gain[i]/ph2Mip)*50) ;
	  sumMult += Int_t (qtCh/sumMultCoeff)  ;

	  // put slewing
	  TGraph *fu=(TGraph*) fParam ->GetWalk(i);
	  Float_t slew=fu->Eval(Float_t(qtCh));

	  //	  trCFD=trCFD-Int_t(fMaxValue[i]-slew);
	  trCFD = trCFD + slew; //for the same channel as cosmic
	  ftimeCFD->AddAt(Int_t (trCFD),i);
	  trLED = Int_t(trCFD  + sl );
	  ftimeLED->AddAt(trLED,i);
	  AliDebug(10,Form("  pmt %i : time in ns %f time in channels %i  LEd %i  ",  i, timeGaus[i],trCFD, trLED ));
	  AliDebug(10,Form(" qt in MIP %f led-cfd in  %f qt in channels %f   ",qt, sl, qtCh));

	}
      } //pmt loop

    //folding with alignmentz position distribution
    if( besttimeC > 10000. && besttimeC <15000)
      bestCTDC=Int_t ((besttimeC+timeDelayCFD[pmtBestC])
			 /channelWidth);

    if( besttimeA > 10000. && besttimeA <15000)
      bestATDC=Int_t ((besttimeA+timeDelayCFD[pmtBestA])
			/channelWidth);

    if (bestATDC < 99999 && bestCTDC < 99999)
      {
	timeDiff=Int_t (((besttimeC-besttimeA)+1000*delayVertex)
			/channelWidth);
	meanTime=Int_t (((besttimeC+besttimeA)/2. )/channelWidth);
      }

    if (sumMult > threshold){
      fSumMult =  Int_t (1000.* TMath::Log(Double_t(sumMult) / Double_t(sumMultCoeff))
			 /channelWidth);
      AliDebug(10,Form("summult mv %i   mult  in chammens %i in ps %i ",
		      sumMult, fSumMult, fSumMult*channelWidth));
    }

    fT0->AddDigit(bestATDC,bestCTDC,meanTime,timeDiff,fSumMult, refpoint,
		       ftimeCFD,fADC0,ftimeLED,fADC);

      AliDebug(10,Form(" Digits wrote refpoint %i bestATDC %i bestCTDC %i  meanTime %i  timeDiff %i fSumMult %i ",refpoint ,bestATDC,bestCTDC,meanTime,timeDiff,fSumMult ));
    pOutStartLoader->UnloadHits();
  } //input streams loop

    //load digits
    pOutStartLoader->LoadDigits("UPDATE");
    TTree *treeD  = pOutStartLoader->TreeD();
    if (treeD == 0x0) {
      pOutStartLoader->MakeTree("D");
      treeD = pOutStartLoader->TreeD();
    }
    treeD->Reset();
    fT0  = (AliT0*)outRL ->GetAliRun()->GetDetector("T0");
    // Make a branch in the tree
    fT0->MakeBranch("D");
     treeD->Fill();

     pOutStartLoader->WriteDigits("OVERWRITE");

     fT0->ResetDigits();
     pOutStartLoader->UnloadDigits();

}
<commit_msg>with calibration up to 50MIPs it not crashes on very central PbPb events, so i removed protection<commit_after>
/**************************************************************************
 * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

/******************************************************************
 *    Produde digits from hits
 *       digits is TObject and includes
 *	We are writing array if C & A  TDC
 *	C & A  ADC (will need for slow simulation)
 *	TOF first particle C & A
 *	mean time and time difference (vertex position)
 *
 *      Alla.Maevskaya@cern.ch
 ****************************************************************/

#include <TArrayI.h>
#include <TFile.h>
#include <TGraph.h>
#include <TH1F.h>
#include <TMath.h>
#include <TRandom.h>
#include <TTree.h>

#include "AliLog.h"
#include "AliT0Digitizer.h"
#include "AliT0.h"
#include "AliT0hit.h"
#include "AliT0digit.h"
#include "AliRunDigitizer.h"
#include "AliRun.h"
#include <AliLoader.h>
#include <AliRunLoader.h>
#include <stdlib.h>
#include "AliT0Parameters.h"

ClassImp(AliT0Digitizer)

//___________________________________________
  AliT0Digitizer::AliT0Digitizer()  :AliDigitizer(),
				     fT0(0),
				     fHits(0),
				     fdigits(0),
				     ftimeCFD(new TArrayI(24)),
				     ftimeLED (new TArrayI(24)),
				     fADC(new TArrayI(24)),
				     fADC0 (new TArrayI(24)),
				     fSumMult(0),
				     fAmpLED(0),
                                     fAmpQTC(0),
				     fParam(0)

{
// Default ctor - don't use it
  ;
}

//___________________________________________
AliT0Digitizer::AliT0Digitizer(AliRunDigitizer* manager)
  :AliDigitizer(manager),
   fT0(0),
   fHits(0),
   fdigits(0),
   ftimeCFD(new TArrayI(24)),
   ftimeLED (new TArrayI(24)),
   fADC(new TArrayI(24)),
   fADC0 (new TArrayI(24)),
   fSumMult(0),
   fAmpLED(0),
   fAmpQTC(0),
   fParam(0)
{
// ctor which should be used

  AliDebug(1,"processed");
  fParam = AliT0Parameters::Instance();
  fParam->Init();

  for (Int_t i=0; i<24; i++){
    TGraph* gr = fParam ->GetAmpLED(i);
    Int_t np = gr->GetN();
    Double_t *x = gr->GetX();
    Double_t *y = gr->GetY();

    Double_t *x1 = new Double_t[np];
    Double_t *y1 = new Double_t[np];
    for (Int_t ii=0; ii<np; ii++) {
      y1[ii]=y[np-ii-1];
      x1[ii]=x[np-ii-1];
    }

    TGraph *grInverse = new TGraph(np,y1,x1);
    fAmpLED.AddAtAndExpand(grInverse,i);
  }
  for (Int_t i=0; i<24; i++){
    TGraph* grq = fParam ->GetQTC(i);
    Int_t npq = grq->GetN();
    Double_t *xq = grq->GetX();
    Double_t *yq = grq->GetY();
    Double_t *x1q = new Double_t[npq];
    Double_t *y1q = new Double_t[npq];
    for (Int_t ii=1; ii<npq; ii++) {
      y1q[ii]=yq[ii-1];
      x1q[ii]=xq[ii-1];
    }
  TGraph *grInverseQTC = new TGraph(npq,y1q,x1q);
  fAmpQTC.AddAtAndExpand(grInverseQTC,i);
  }
}

//------------------------------------------------------------------------
AliT0Digitizer::~AliT0Digitizer()
{
// Destructor

  AliDebug(1,"T0");

  delete ftimeCFD;
  delete fADC;
  delete ftimeLED;
  delete  fADC0;
  //  delete fAmpLED;
}

//------------------------------------------------------------------------
Bool_t AliT0Digitizer::Init()
{
// Initialization
  AliDebug(1," Init");
 return kTRUE;
}

//---------------------------------------------------------------------
void AliT0Digitizer::Exec(Option_t* /*option*/)
{

  /*
    Produde digits from hits
        digits is TObject and includes
	We are writing array if C & A  TDC
	C & A  ADC (will need for slow simulation)
	TOF first particle C & A
	mean time and time difference (vertex position)

  */

  //output loader
  AliRunLoader *outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
  AliLoader * pOutStartLoader = outRL->GetLoader("T0Loader");

  AliDebug(1,"start...");
  //input loader
  //
  // From hits to digits
  //
  Int_t hit, nhits;
  Int_t countE[24];
  Int_t volume, pmt, trCFD, trLED;
  Float_t sl, qt;
  Int_t  bestATDC=0;
  Int_t  bestCTDC=0;
  Float_t qtCh=0;
  Float_t time[24], besttime[24], timeGaus[24] ;
  //Q->T-> coefficients !!!! should be asked!!!
  Float_t timeDelayCFD[24];
  Int_t threshold =50; //photoelectrons
  Float_t zdetA, zdetC;
  Int_t sumMultCoeff = 100;
  Int_t refpoint=0;

  Int_t ph2Mip = fParam->GetPh2Mip();
  Float_t channelWidth = fParam->GetChannelWidth() ;
  Float_t delayVertex = fParam->GetTimeDelayTVD();

  zdetC = TMath::Abs(fParam->GetZPosition("T0/C/PMT1"));
  zdetA  = TMath::Abs(fParam->GetZPosition("T0/A/PMT15"));

  //  printf(" !!!!!Z det A = %f C = % f",zdetA,zdetC);
  AliT0hit  *startHit;
  TBranch *brHits=0;

  Int_t nFiles=fManager->GetNinputs();
  for (Int_t inputFile=0; inputFile<nFiles;  inputFile++) {
    if (inputFile < nFiles-1) {
      AliWarning(Form("ignoring input stream %d", inputFile));
      continue;

    }

    Float_t besttimeC=99999.;
    Float_t besttimeA=99999.;
    Int_t pmtBestC=99999;
    Int_t pmtBestA=99999;
    Int_t timeDiff=99999, meanTime=99999;
    Int_t sumMult =0;   fSumMult=0;
    bestATDC = 99999;  bestCTDC = 99999;

    ftimeCFD -> Reset();
    fADC -> Reset();
    fADC0 -> Reset();
    ftimeLED ->Reset();
    for (Int_t i0=0; i0<24; i0++)
      {
	time[i0]=besttime[i0]=timeGaus[i0]=999999; countE[i0]=0;
      }
    AliRunLoader * inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
    AliLoader * pInStartLoader = inRL->GetLoader("T0Loader");
    if (!inRL->GetAliRun()) inRL->LoadgAlice();
    fT0  = (AliT0*)inRL ->GetAliRun()->GetDetector("T0");

       //read Hits
    pInStartLoader->LoadHits("READ");//probably it is necessary to load them before
    fHits = fT0->Hits ();
    TTree *th = pInStartLoader->TreeH();
    brHits = th->GetBranch("T0");
    if (brHits) {
      fT0->SetHitsAddressBranch(brHits);
    }else{
      AliWarning("Branch T0 hit not found for this event");
      // fT0->AddDigit(bestATDC,bestCTDC,meanTime,timeDiff,fSumMult, refpoint,
      //	       ftimeCFD,fADC0,ftimeLED,fADC);
      continue;
    }
    Int_t ntracks    = (Int_t) th->GetEntries();

    if (ntracks<=0) return;
    // Start loop on tracks in the hits containers
    for (Int_t track=0; track<ntracks;track++) {
      brHits->GetEntry(track);
      nhits = fHits->GetEntriesFast();
      for (hit=0;hit<nhits;hit++)
	{
	  startHit   = (AliT0hit*) fHits->UncheckedAt(hit);
	  if (!startHit) {
 	    AliError("The unchecked hit doesn't exist");
	    break;
	  }
	  pmt=startHit->Pmt();
	  Int_t numpmt=pmt-1;
	  Double_t e=startHit->Etot();
	  volume = startHit->Volume();

	  if(e>0 ) {
	    countE[numpmt]++;
	    besttime[numpmt] = startHit->Time();
	    if(besttime[numpmt]<time[numpmt])
	      {
		time[numpmt]=besttime[numpmt];
	      }
	  } //photoelectron accept
	} //hits loop
    } //track loop

    //spread time A&C by 25ps   && besttime
    Float_t c = 0.0299792; // cm/ps

    Float_t koef=(zdetA-zdetC)/c; //correction position difference by cable
    for (Int_t ipmt=0; ipmt<12; ipmt++){
      if(countE[ipmt] > threshold) {
	timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25)+koef;
	if(timeGaus[ipmt]<besttimeC){
	  besttimeC=timeGaus[ipmt]; //timeC
	  pmtBestC=ipmt;}
      }
    }
    for ( Int_t ipmt=12; ipmt<24; ipmt++){
      if(countE[ipmt] > threshold) {
	timeGaus[ipmt]=gRandom->Gaus(time[ipmt],25);
	if(timeGaus[ipmt]<besttimeA) {
	  besttimeA=timeGaus[ipmt]; //timeA
	  pmtBestA=ipmt;}
      }
    }

    timeDelayCFD[0] = fParam->GetTimeDelayCFD(0);

    for (Int_t i=0; i<24; i++)
      {
       	Float_t  al = countE[i];
	if (al>threshold && timeGaus[i]<50000 ) {
	  //fill ADC
	  // QTC procedure:
	  // phe -> mV 0.3; 1MIP ->500phe -> ln (amp (mV)) = 5;
	  // max 200ns, HIJING  mean 50000phe -> 15000mv -> ln = 15 (s zapasom)
	  // channel 25ps
	  qt= al/ph2Mip;  // 50mv/Mip amp in mV
	  // before will we have calibration for high multiplicity
	  //	  if (qt > 115.) qt =115.; //must be fix!!!
	  //  fill TDC
	  timeDelayCFD[i] = fParam->GetTimeDelayCFD(i);
 	  trCFD = Int_t (timeGaus[i]/channelWidth + timeDelayCFD[i]);

	  TGraph* gr = ((TGraph*)fAmpLED.At(i));
	  sl = gr->Eval(qt);

	  TGraph* gr1 = ((TGraph*)fAmpQTC.At(i));
	  qtCh = gr1->Eval(qt);
	  fADC0->AddAt(0,i);
	  fADC->AddAt(qtCh,i);
	  //	  sumMult += Int_t ((al*gain[i]/ph2Mip)*50) ;
	  sumMult += Int_t (qtCh/sumMultCoeff)  ;

	  // put slewing
	  TGraph *fu=(TGraph*) fParam ->GetWalk(i);
	  Float_t slew=fu->Eval(Float_t(qtCh));

	  //	  trCFD=trCFD-Int_t(fMaxValue[i]-slew);
	  trCFD = trCFD + slew; //for the same channel as cosmic
	  ftimeCFD->AddAt(Int_t (trCFD),i);
	  trLED = Int_t(trCFD  + sl );
	  ftimeLED->AddAt(trLED,i);
	  AliDebug(10,Form("  pmt %i : time in ns %f time in channels %i  LEd %i  ",  i, timeGaus[i],trCFD, trLED ));
	  AliDebug(10,Form(" qt in MIP %f led-cfd in  %f qt in channels %f   ",qt, sl, qtCh));

	}
      } //pmt loop

    //folding with alignmentz position distribution
    if( besttimeC > 10000. && besttimeC <15000)
      bestCTDC=Int_t ((besttimeC+timeDelayCFD[pmtBestC])
			 /channelWidth);

    if( besttimeA > 10000. && besttimeA <15000)
      bestATDC=Int_t ((besttimeA+timeDelayCFD[pmtBestA])
			/channelWidth);

    if (bestATDC < 99999 && bestCTDC < 99999)
      {
	timeDiff=Int_t (((besttimeC-besttimeA)+1000*delayVertex)
			/channelWidth);
	meanTime=Int_t (((besttimeC+besttimeA)/2. )/channelWidth);
      }

    if (sumMult > threshold){
      fSumMult =  Int_t (1000.* TMath::Log(Double_t(sumMult) / Double_t(sumMultCoeff))
			 /channelWidth);
      AliDebug(10,Form("summult mv %i   mult  in chammens %i in ps %i ",
		      sumMult, fSumMult, fSumMult*channelWidth));
    }

    fT0->AddDigit(bestATDC,bestCTDC,meanTime,timeDiff,fSumMult, refpoint,
		       ftimeCFD,fADC0,ftimeLED,fADC);

      AliDebug(10,Form(" Digits wrote refpoint %i bestATDC %i bestCTDC %i  meanTime %i  timeDiff %i fSumMult %i ",refpoint ,bestATDC,bestCTDC,meanTime,timeDiff,fSumMult ));
    pOutStartLoader->UnloadHits();
  } //input streams loop

    //load digits
    pOutStartLoader->LoadDigits("UPDATE");
    TTree *treeD  = pOutStartLoader->TreeD();
    if (treeD == 0x0) {
      pOutStartLoader->MakeTree("D");
      treeD = pOutStartLoader->TreeD();
    }
    treeD->Reset();
    fT0  = (AliT0*)outRL ->GetAliRun()->GetDetector("T0");
    // Make a branch in the tree
    fT0->MakeBranch("D");
     treeD->Fill();

     pOutStartLoader->WriteDigits("OVERWRITE");

     fT0->ResetDigits();
     pOutStartLoader->UnloadDigits();

}
<|endoftext|>


<commit_before>#ifndef ALEPH_TIMER_HH__
#define ALEPH_TIMER_HH__

#include <chrono>

namespace aleph
{

namespace utilities
{

class Timer
{
public:

  /** Starts the timer */
  Timer()
    : _start( std::chrono::steady_clock::now() )
  {
  }

  /** Restarts the timer */
  void restart()
  {
    _start = std::chrono::steady_clock::now();
  }

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

  /** @returns Elapsed time in (fractional) seconds */
  double elapsed_s() const
  {
    return std::chrono::duration<double>( now() - _start ).count();
  }

  /** @returns Elapsed time in (fractional) milliseconds */
  double elapsed_ms() const
  {
    return std::chrono::duration<double, std::milli>( now() - _start ).count();
  }

  /** @returns Elapsed time in (fractional) microseconds */
  double elapsed_mu() const
  {
    return std::chrono::duration<double, std::micro>( now() - _start ).count();
  }

  /** @returns Elapsed time in (fractional) nanoseconds */
  double elapsed_ns() const
  {
    return std::chrono::duration<double, std::nano>( now() - _start ).count();
  }

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

  /** @returns Current time */
  std::chrono::steady_clock::time_point now() const
  {
    return std::chrono::steady_clock::now();
  }

private:

  /** Start time; will be set automatically in the constructor */
  std::chrono::steady_clock::time_point _start;
};

} // namespace utilities

} // namespace aleph

#endif
<commit_msg>Fixed header guard<commit_after>#ifndef ALEPH_UTILITIES_TIMER_HH__
#define ALEPH_UTILITIES_TIMER_HH__

#include <chrono>

namespace aleph
{

namespace utilities
{

class Timer
{
public:

  /** Starts the timer */
  Timer()
    : _start( std::chrono::steady_clock::now() )
  {
  }

  /** Restarts the timer */
  void restart()
  {
    _start = std::chrono::steady_clock::now();
  }

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

  /** @returns Elapsed time in (fractional) seconds */
  double elapsed_s() const
  {
    return std::chrono::duration<double>( now() - _start ).count();
  }

  /** @returns Elapsed time in (fractional) milliseconds */
  double elapsed_ms() const
  {
    return std::chrono::duration<double, std::milli>( now() - _start ).count();
  }

  /** @returns Elapsed time in (fractional) microseconds */
  double elapsed_mu() const
  {
    return std::chrono::duration<double, std::micro>( now() - _start ).count();
  }

  /** @returns Elapsed time in (fractional) nanoseconds */
  double elapsed_ns() const
  {
    return std::chrono::duration<double, std::nano>( now() - _start ).count();
  }

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

  /** @returns Current time */
  std::chrono::steady_clock::time_point now() const
  {
    return std::chrono::steady_clock::now();
  }

private:

  /** Start time; will be set automatically in the constructor */
  std::chrono::steady_clock::time_point _start;
};

} // namespace utilities

} // namespace aleph

#endif
<|endoftext|>


<commit_before>#include "lirch_setup_wizard.h"
#include "ui_lirch_setup_wizard.h"

LirchSetupWizard::LirchSetupWizard(QWidget *parent) :
	QWizard(parent),
	ui(new Ui::LirchSetupWizard)
{
	ui->setupUi(this);
	// Configure fields (nick is mandatory)
	// ui->nickname_config_page->registerField("UserSettings.nick*", ui->nickname_lineedit);
	// ui->nickname_config_page->registerField("UserSettings.nick_is_default", ui->nickname_checkbox);
	// ui->logging_config_page->registerField("Logger.log_default", ui->logging_type_default);
	// ui->logging_config_page->registerField("Logger.log_everything", ui->logging_type_on);
	// ui->logging_config_page->registerField("Logger.log_nothing", ui->logging_type_off);
	// ui->logging_config_page->registerField("Logger.root_directory", ui->logging_dir_lineedit);
	// TODO validate file path exists ^
}

LirchSetupWizard::~LirchSetupWizard()
{
    delete ui;
}

QString LirchSetupWizard::get_nick() const
{
	//return field("UserSettings.nick").value<QString>();
	return ui->nickname_lineedit->text().trimmed();
}

bool LirchSetupWizard::nick_is_default() const
{
	//return field("UserSettings.nick_is_default").value<bool>();
	return ui->nickname_checkbox->isChecked();
}

logging_message::logging_mode LirchSetupWizard::get_logging_mode() const
{
	/*
	if (field("Logger.log_default").value<bool>()) {
		return logging_message::logging_mode::DEFAULT;
	}
	if (field("Logger.log_everything").value<bool>()) {
		return logging_message::logging_mode::ON;
	}
	if (field("Logger.log_nothing").value<bool>()) {
		return logging_message::logging_mode::OFF;
	}
	*/
	if (ui->logging_type_default->isChecked()) {
		return logging_message::logging_mode::DEFAULT;
	}
	if (ui->logging_type_on->isChecked()) {
		return logging_message::logging_mode::ON;
	}
	if (ui->logging_type_off->isChecked()) {
		return logging_message::logging_mode::OFF;
	}
	return logging_message::logging_mode::DEFAULT;
}

QString LirchSetupWizard::get_logging_directory() const
{
	//return field("Logger.root_directory").value<QString>();
	return ui->logging_dir_lineedit->text().trimmed();
}

void LirchSetupWizard::changeEvent(QEvent *e)
{
	QWizard::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		ui->retranslateUi(this);
		break;
	default:
		break;
	}
}
<commit_msg>Made the default default nick fill in the wizard<commit_after>#include "lirch_setup_wizard.h"
#include "ui_lirch_setup_wizard.h"

LirchSetupWizard::LirchSetupWizard(QWidget *parent) :
	QWizard(parent),
	ui(new Ui::LirchSetupWizard)
{
	ui->setupUi(this);
	ui->nickname_lineedit->setText(tr(LIRCH_DEFAULT_NICK));
	// Configure fields (nick is mandatory)
	// ui->nickname_config_page->registerField("UserSettings.nick*", ui->nickname_lineedit);
	// ui->nickname_config_page->registerField("UserSettings.nick_is_default", ui->nickname_checkbox);
	// ui->logging_config_page->registerField("Logger.log_default", ui->logging_type_default);
	// ui->logging_config_page->registerField("Logger.log_everything", ui->logging_type_on);
	// ui->logging_config_page->registerField("Logger.log_nothing", ui->logging_type_off);
	// ui->logging_config_page->registerField("Logger.root_directory", ui->logging_dir_lineedit);
	// TODO validate file path exists ^
}

LirchSetupWizard::~LirchSetupWizard()
{
    delete ui;
}

QString LirchSetupWizard::get_nick() const
{
	//return field("UserSettings.nick").value<QString>();
	return ui->nickname_lineedit->text().trimmed();
}

bool LirchSetupWizard::nick_is_default() const
{
	//return field("UserSettings.nick_is_default").value<bool>();
	return ui->nickname_checkbox->isChecked();
}

logging_message::logging_mode LirchSetupWizard::get_logging_mode() const
{
	/*
	if (field("Logger.log_default").value<bool>()) {
		return logging_message::logging_mode::DEFAULT;
	}
	if (field("Logger.log_everything").value<bool>()) {
		return logging_message::logging_mode::ON;
	}
	if (field("Logger.log_nothing").value<bool>()) {
		return logging_message::logging_mode::OFF;
	}
	*/
	if (ui->logging_type_default->isChecked()) {
		return logging_message::logging_mode::DEFAULT;
	}
	if (ui->logging_type_on->isChecked()) {
		return logging_message::logging_mode::ON;
	}
	if (ui->logging_type_off->isChecked()) {
		return logging_message::logging_mode::OFF;
	}
	return logging_message::logging_mode::DEFAULT;
}

QString LirchSetupWizard::get_logging_directory() const
{
	//return field("Logger.root_directory").value<QString>();
	return ui->logging_dir_lineedit->text().trimmed();
}

void LirchSetupWizard::changeEvent(QEvent *e)
{
	QWizard::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange:
		ui->retranslateUi(this);
		break;
	default:
		break;
	}
}
<|endoftext|>


<commit_before>//#define ALLEGRO_STATICLINK 1
#include <allegro5/allegro.h>
#include <dynamic_menu.h>
#include <iostream>
#include <keyboard.h>
#include <menu_helper.h>
#include <screen_reader.h>
#include <sound.h>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <misc.h>

ALLEGRO_DISPLAY* game_window(string gameTitle)
{
log_open("error.log");
if(!al_init()) {
log("Could not initialize allegro.\n");
return NULL;
}
if(!al_install_audio()) {
log("Could not install audio subsystem.\n");
al_uninstall_system();
return NULL;
}
if(!al_install_keyboard()) {
log("Could not install keyboard hooks.\n");
al_uninstall_audio();
al_uninstall_system();
return NULL;
}
if(!al_init_acodec_addon()) {
log("Could not initialize codec routines.\n");
al_uninstall_audio();
al_uninstall_keyboard();
al_uninstall_system();
return NULL;
}
ALLEGRO_DISPLAY* disp = al_create_display(640,480);
if(!disp) {
return NULL;
}
else {
al_set_window_title(disp, gameTitle.c_str());
return disp;
}
}

int end_game(ALLEGRO_DISPLAY* disp)
{
al_uninstall_audio();
al_uninstall_keyboard();
al_destroy_display(disp);
al_uninstall_system();
return 0;
}

string get_cpu_name()
{
string nameList[] = {"Alicia",
"April",
"Alonzo",
"Anaya",
"Andrew",
"Anthony",
"Billy",
"Burt",
"Cayden",
"Dorothy",
"Draken",
"Dave",
"Ember",
"Faye",
"George",
"Janet",
"Jenna",
"Jeniffer",
"Jeremiah",
"Kendell",
"Kris",
"Kyle",
"Labesia",
"Maggie",
"Mellisa",
"Michael",
"Rebecca",
"Scott",
"Storm",
"Terence",
"Tux",
"Tyler",
"Victoria"};
int i = rand() % (sizeof(nameList)/sizeof(nameList[0])); // generate a number within the size of the array nameList.
return nameList[i];
}

FILE* fi = NULL;
int log_open(string file) {
fi = fopen(file.c_str(), "w");
if(!fi) {
return false;
}
return true;
}

void credits(ALLEGRO_DISPLAY* disp, string gameName)
{
string credits[] = {gameName + "! brought to you by 2MB Solutions!",
"Billy Wolfe. Coder and designer. storm dragon dot tk",
"Michael Taboada. Coder and designer. Michael Taboada dot m e",
"Back to main menu"};
dynamic_menu* creditsMenu = create_menu(vector<string>(credits, credits+4), vector<string>());
creditsMenu->set_display(disp);
creditsMenu->run_extended("", "", 1, true);
delete creditsMenu;
}

void log(string message) {
if(fi) {
fprintf(fi, message.c_str());
}
}

void log_close() {
if(fi) {
fclose(fi);
fi = NULL;
}
}

<commit_msg>Fixed slight issues in file names.<commit_after>//#define ALLEGRO_STATICLINK 1
#include <allegro5/allegro.h>
#include <dynamic_menu.h>
#include <iostream>
#include <keyboard.h>
#include <menu_helper.h>
#include <screen_reader.h>
#include <sound.h>
#include <sstream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <misc.h>

ALLEGRO_DISPLAY* game_window(string gameTitle)
{
log_open("errors.log");
if(!al_init()) {
log("Could not initialize allegro.\n");
return NULL;
}
if(!al_install_audio()) {
log("Could not install audio subsystem.\n");
al_uninstall_system();
return NULL;
}
if(!al_install_keyboard()) {
log("Could not install keyboard hooks.\n");
al_uninstall_audio();
al_uninstall_system();
return NULL;
}
if(!al_init_acodec_addon()) {
log("Could not initialize codec routines.\n");
al_uninstall_audio();
al_uninstall_keyboard();
al_uninstall_system();
return NULL;
}
ALLEGRO_DISPLAY* disp = al_create_display(640,480);
if(!disp) {
return NULL;
}
else {
al_set_window_title(disp, gameTitle.c_str());
return disp;
}
}

int end_game(ALLEGRO_DISPLAY* disp)
{
al_uninstall_audio();
al_uninstall_keyboard();
al_destroy_display(disp);
al_uninstall_system();
return 0;
}

string get_cpu_name()
{
string nameList[] = {"Alicia",
"April",
"Alonzo",
"Anaya",
"Andrew",
"Anthony",
"Billy",
"Burt",
"Cayden",
"Dorothy",
"Draken",
"Dave",
"Ember",
"Faye",
"George",
"Janet",
"Jenna",
"Jeniffer",
"Jeremiah",
"Kendell",
"Kris",
"Kyle",
"Labesia",
"Maggie",
"Mellisa",
"Michael",
"Rebecca",
"Scott",
"Storm",
"Terence",
"Tux",
"Tyler",
"Victoria"};
int i = rand() % (sizeof(nameList)/sizeof(nameList[0])); // generate a number within the size of the array nameList.
return nameList[i];
}

FILE* fi = NULL;
int log_open(string file) {
fi = fopen(file.c_str(), "w");
if(!fi) {
return false;
}
return true;
}

void credits(ALLEGRO_DISPLAY* disp, string gameName)
{
string credits[] = {gameName + "! brought to you by 2MB Solutions!",
"Billy Wolfe. Coder and designer. storm dragon dot tk",
"Michael Taboada. Coder and designer. Michael Taboada dot m e",
"Back to main menu"};
dynamic_menu* creditsMenu = create_menu(vector<string>(credits, credits+4), vector<string>());
creditsMenu->set_display(disp);
creditsMenu->run_extended("", "", 1, true);
delete creditsMenu;
}

void log(string message) {
if(fi) {
fprintf(fi, message.c_str());
}
}

void log_close() {
if(fi) {
fclose(fi);
fi = NULL;
}
}

<|endoftext|>