<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2014 Lukas Kemmer
//
// 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.

#ifndef FAINT_WINDOW_APP_CONTEXT_HH
#define FAINT_WINDOW_APP_CONTEXT_HH
#include "app/app-context.hh"
#include "app/faint-common-cursors.hh"
#include "app/faint-slider-cursors.hh"
#include "gui/canvas-panel.hh" // Fixme
#include "gui/command-window.hh"
#include "gui/dialogs/resize-dialog-options.hh" // Fixme: impl
#include "gui/faint-window.hh" // Fixme: Consider forward declaration
#include "gui/transparency-style.hh" // Fixme: impl
#include "tools/tool.hh"
#include "util/bound-setting.hh" // Fixme: For BoundSetting
#include "util/dumb-ptr.hh" // Fixme: impl
#include "util/grid.hh" // Fixme: impl

class wxStatusBar;

namespace faint{

class Art;
class Canvas;
class FilePath;
class FaintWindow;
class HelpFrame;
class InterpreterFrame;
class TabCtrl;

class SBInterface final : public StatusInterface {
public:
  SBInterface(wxStatusBar&);
  void SetMainText(const utf8_string& text) override;
  void SetText(const utf8_string& text, int field=0) override;
  void Clear() override;

  SBInterface& operator=(const SBInterface&) = delete;
private:
  wxStatusBar& m_statusbar;
};

using from_control = LessDistinct<bool, 0>;

class FaintDialogContext final : public DialogContext{
public:
  FaintDialogContext(AppContext&, const Art&, FaintWindow&);

  SliderCursors& GetSliderCursors() override;
  CommonCursors& GetCommonCursors() override;
  void Show(std::unique_ptr<CommandWindow>&& w) override;
  void UpdateSettings(const Settings&);
  void Reinitialize();
  Optional<CommandWindow&> ShownWindow();
  void Close();

private:
  void BeginModalDialog() override;
  void EndModalDialog() override;
  void OnClosed(BitmapCommand*);

  AppContext& m_app;
  std::unique_ptr<CommandWindow> m_commandWindow;
  FaintCommonCursors m_commonCursors;
  FaintWindow& m_faintWindow;
  FaintSliderCursors m_sliderCursors;
  std::unique_ptr<WindowFeedback> m_windowFeedback;
};

class FaintWindowExtraOverlay final : public ExtraOverlay{
public:
  // Fixme: Weird class. Use the WindowFeedback instead?
  FaintWindowExtraOverlay(FaintDialogContext&);
  void Draw(FaintDC& dc, Overlays& overlays, const PosInfo& info) override;

  FaintWindowExtraOverlay& operator=(FaintWindowExtraOverlay&) = delete;
private:
  FaintDialogContext& m_dialogContext;
};

class FaintWindowInteraction final : public Interaction{
public:
  FaintWindowInteraction(FaintDialogContext&);
  bool MouseMove(const PosInfo&) override;

  FaintWindowInteraction& operator=(const FaintWindowInteraction&) = delete;
private:
  FaintDialogContext& m_ctx;
};

class FaintWindowContext final : public AppContext {
public:
  FaintWindowContext(FaintWindow&, const Art&,
    wxStatusBar&, HelpFrame&, InterpreterFrame&);
  void AddFormat(Format*) override;
  void AddToPalette(const Paint&) override;
  void BeginModalDialog() override;
  void BeginTextEntry() override;
  void Close(Canvas& canvas) override;
  void DialogOpenFile() override;
  void DialogSaveAs(Canvas& canvas, bool backup) override;
  void EndModalDialog() override;
  void EndTextEntry() override;
  bool Exists(const CanvasId&) override;
  bool FaintWindowFocused() const override;
  BoolSetting::ValueType Get(const BoolSetting&) override;
  StringSetting::ValueType Get(const StringSetting&) override;
  IntSetting::ValueType Get(const IntSetting&) override;
  PaintSetting::ValueType Get(const PaintSetting&) override;
  FloatSetting::ValueType Get(const FloatSetting&) override;
  Interaction& GetInteraction() override;
  ExtraOverlay& GetExtraOverlay() override;
  Canvas& GetActiveCanvas() override;
  Tool* GetActiveTool() override;
  Canvas& GetCanvas(const Index&) override;
  Canvas& GetCanvas(const CanvasId&) override;
  Index GetCanvasCount() const override;
  Grid GetDefaultGrid() const override;
  ImageInfo GetDefaultImageInfo() override;
  FaintDialogContext& GetDialogContext() override;
  std::vector<Format*> GetFormats() override;
  ResizeDialogOptions GetDefaultResizeDialogOptions() const override;
  Layer GetLayerType() const override;
  IntPoint GetMousePos() override;
  StatusInterface& GetStatusInfo(); // Non virtual
  ToolId GetToolId() const override;
  Settings GetToolSettings() const override;
  const TransparencyStyle& GetTransparencyStyle() const override;
  bool IsFullScreen() const override;
  Canvas* Load(const FilePath&, const change_tab&) override;
  void Load(const FileList&) override;
  Canvas* LoadAsFrames(const FileList& paths,
    const change_tab& changeTab) override;
  void Maximize() override;
  void MaximizeInterpreter() override;
  bool ModalDialogShown() const override;
  Canvas& NewDocument(const ImageInfo& info) override;
  Canvas& NewDocument(ImageProps&& props) override;
  void NextTab() override;
  void PreviousTab() override;
  void QueueLoad(const FileList& filenames) override;
  void Quit() override;
  void RaiseWindow() override;
  bool Save(Canvas& canvas) override;
  void SelectTool(ToolId id) override;
  void Set(const BoolSetting&, BoolSetting::ValueType) override;
  void Set(const StringSetting&, const StringSetting::ValueType&) override;
  void Set(const IntSetting&, IntSetting::ValueType) override;
  void Set(const PaintSetting&, PaintSetting::ValueType) override;
  void Set(const FloatSetting&, FloatSetting::ValueType) override;
  void SetActiveCanvas(const CanvasId&) override;
  void SetDefaultGrid(const Grid&) override;
  void SetDefaultResizeDialogOptions(const ResizeDialogOptions& opts) override;
  void SetInterpreterBackground(const ColRGB& c) override;
  void SetInterpreterTextColor(const ColRGB& c) override;
  void SetPalette(const PaintMap& paintMap) override;
  void SetTransparencyStyle(const TransparencyStyle& style) override;
  void SetLayer(Layer layer) override;
  void ModalFull(const dialog_func& show_dialog) override;
  void Modal(const bmp_dialog_func& show_dialog) override;
  void ToggleHelpFrame() override;
  void TogglePythonConsole() override;
  void ShowColorPanel(bool show) override;
  void ShowPythonConsole() override;
  void ShowStatusbar(bool show) override;
  void ShowToolPanel(bool show) override;
  int TabletGetCursor() override;

  // Note: Not an override, used directly by FaintWindow
  void TabletSetCursor(int tabletCursor);

  void ToggleFullScreen(bool) override;
  void ToggleMaximize() override;
  void UpdateShownSettings() override;
  void UpdateToolSettings(const Settings&) override;
  void SetTabCtrl(TabCtrl*); // Non virtual

private:
  FaintDialogContext m_dialogContext;
  FaintWindowExtraOverlay m_extraOverlay;
  FaintWindow& m_faintWindow;
  HelpFrame& m_helpFrame;
  FaintWindowInteraction m_interaction;
  InterpreterFrame& m_interpreterFrame;
  int m_modalDialog;
  SBInterface m_statusbar;
  Grid m_defaultGrid;
  ResizeDialogOptions m_defaultResizeSettings;
  TransparencyStyle m_transparencyStyle;
  int m_tabletCursor;
  dumb_ptr<TabCtrl> m_tabControl;
};

template<typename T>
void change_setting(FaintWindow& window,
  const T& setting,
  typename T::ValueType value,
  const from_control& fromControl,
  FaintDialogContext& dialogContext)
{
  dialogContext.ShownWindow().Visit(
    [&](CommandWindow& w){
      const auto& windowSettings(w.GetSettings());
      if (windowSettings.Has(setting)){
        // Fixme: Silly
        dialogContext.UpdateSettings(with(windowSettings, setting, value));
        // w.UpdateSettings(with(windowSettings, setting, value));
      }
    },
    [](){});

  Tool* tool = window.GetActiveTool();
  if (tool->GetSettings().Has(setting)){
    bool toolModified = tool->Set({setting, value});
    if (toolModified) {
      window.GetActiveCanvas().Refresh();
    }
    if (tool->EatsSettings()){
      if (!fromControl.Get()){
        window.UpdateShownSettings();
      }
      return;
    }
  }
  window.GetToolSettings().Set(setting, value);
  if (!fromControl.Get()){
    window.UpdateShownSettings();
  }
}

} // namespace

#endif
<commit_msg>Removed unnecessary include.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2014 Lukas Kemmer
//
// 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.

#ifndef FAINT_WINDOW_APP_CONTEXT_HH
#define FAINT_WINDOW_APP_CONTEXT_HH
#include "app/app-context.hh"
#include "app/faint-common-cursors.hh"
#include "app/faint-slider-cursors.hh"
#include "gui/canvas-panel.hh" // Fixme
#include "gui/command-window.hh"
#include "gui/dialogs/resize-dialog-options.hh" // Fixme: impl
#include "gui/transparency-style.hh" // Fixme: impl
#include "tools/tool.hh"
#include "util/bound-setting.hh" // Fixme: For BoundSetting
#include "util/dumb-ptr.hh" // Fixme: impl
#include "util/grid.hh" // Fixme: impl

class wxStatusBar;

namespace faint{

class Art;
class Canvas;
class FilePath;
class FaintWindow;
class HelpFrame;
class InterpreterFrame;
class TabCtrl;

class SBInterface final : public StatusInterface {
public:
  SBInterface(wxStatusBar&);
  void SetMainText(const utf8_string& text) override;
  void SetText(const utf8_string& text, int field=0) override;
  void Clear() override;

  SBInterface& operator=(const SBInterface&) = delete;
private:
  wxStatusBar& m_statusbar;
};

using from_control = LessDistinct<bool, 0>;

class FaintDialogContext final : public DialogContext{
public:
  FaintDialogContext(AppContext&, const Art&, FaintWindow&);

  SliderCursors& GetSliderCursors() override;
  CommonCursors& GetCommonCursors() override;
  void Show(std::unique_ptr<CommandWindow>&& w) override;
  void UpdateSettings(const Settings&);
  void Reinitialize();
  Optional<CommandWindow&> ShownWindow();
  void Close();

private:
  void BeginModalDialog() override;
  void EndModalDialog() override;
  void OnClosed(BitmapCommand*);

  AppContext& m_app;
  std::unique_ptr<CommandWindow> m_commandWindow;
  FaintCommonCursors m_commonCursors;
  FaintWindow& m_faintWindow;
  FaintSliderCursors m_sliderCursors;
  std::unique_ptr<WindowFeedback> m_windowFeedback;
};

class FaintWindowExtraOverlay final : public ExtraOverlay{
public:
  // Fixme: Weird class. Use the WindowFeedback instead?
  FaintWindowExtraOverlay(FaintDialogContext&);
  void Draw(FaintDC& dc, Overlays& overlays, const PosInfo& info) override;

  FaintWindowExtraOverlay& operator=(FaintWindowExtraOverlay&) = delete;
private:
  FaintDialogContext& m_dialogContext;
};

class FaintWindowInteraction final : public Interaction{
public:
  FaintWindowInteraction(FaintDialogContext&);
  bool MouseMove(const PosInfo&) override;

  FaintWindowInteraction& operator=(const FaintWindowInteraction&) = delete;
private:
  FaintDialogContext& m_ctx;
};

class FaintWindowContext final : public AppContext {
public:
  FaintWindowContext(FaintWindow&, const Art&,
    wxStatusBar&, HelpFrame&, InterpreterFrame&);
  void AddFormat(Format*) override;
  void AddToPalette(const Paint&) override;
  void BeginModalDialog() override;
  void BeginTextEntry() override;
  void Close(Canvas& canvas) override;
  void DialogOpenFile() override;
  void DialogSaveAs(Canvas& canvas, bool backup) override;
  void EndModalDialog() override;
  void EndTextEntry() override;
  bool Exists(const CanvasId&) override;
  bool FaintWindowFocused() const override;
  BoolSetting::ValueType Get(const BoolSetting&) override;
  StringSetting::ValueType Get(const StringSetting&) override;
  IntSetting::ValueType Get(const IntSetting&) override;
  PaintSetting::ValueType Get(const PaintSetting&) override;
  FloatSetting::ValueType Get(const FloatSetting&) override;
  Interaction& GetInteraction() override;
  ExtraOverlay& GetExtraOverlay() override;
  Canvas& GetActiveCanvas() override;
  Tool* GetActiveTool() override;
  Canvas& GetCanvas(const Index&) override;
  Canvas& GetCanvas(const CanvasId&) override;
  Index GetCanvasCount() const override;
  Grid GetDefaultGrid() const override;
  ImageInfo GetDefaultImageInfo() override;
  FaintDialogContext& GetDialogContext() override;
  std::vector<Format*> GetFormats() override;
  ResizeDialogOptions GetDefaultResizeDialogOptions() const override;
  Layer GetLayerType() const override;
  IntPoint GetMousePos() override;
  StatusInterface& GetStatusInfo(); // Non virtual
  ToolId GetToolId() const override;
  Settings GetToolSettings() const override;
  const TransparencyStyle& GetTransparencyStyle() const override;
  bool IsFullScreen() const override;
  Canvas* Load(const FilePath&, const change_tab&) override;
  void Load(const FileList&) override;
  Canvas* LoadAsFrames(const FileList& paths,
    const change_tab& changeTab) override;
  void Maximize() override;
  void MaximizeInterpreter() override;
  bool ModalDialogShown() const override;
  Canvas& NewDocument(const ImageInfo& info) override;
  Canvas& NewDocument(ImageProps&& props) override;
  void NextTab() override;
  void PreviousTab() override;
  void QueueLoad(const FileList& filenames) override;
  void Quit() override;
  void RaiseWindow() override;
  bool Save(Canvas& canvas) override;
  void SelectTool(ToolId id) override;
  void Set(const BoolSetting&, BoolSetting::ValueType) override;
  void Set(const StringSetting&, const StringSetting::ValueType&) override;
  void Set(const IntSetting&, IntSetting::ValueType) override;
  void Set(const PaintSetting&, PaintSetting::ValueType) override;
  void Set(const FloatSetting&, FloatSetting::ValueType) override;
  void SetActiveCanvas(const CanvasId&) override;
  void SetDefaultGrid(const Grid&) override;
  void SetDefaultResizeDialogOptions(const ResizeDialogOptions& opts) override;
  void SetInterpreterBackground(const ColRGB& c) override;
  void SetInterpreterTextColor(const ColRGB& c) override;
  void SetPalette(const PaintMap& paintMap) override;
  void SetTransparencyStyle(const TransparencyStyle& style) override;
  void SetLayer(Layer layer) override;
  void ModalFull(const dialog_func& show_dialog) override;
  void Modal(const bmp_dialog_func& show_dialog) override;
  void ToggleHelpFrame() override;
  void TogglePythonConsole() override;
  void ShowColorPanel(bool show) override;
  void ShowPythonConsole() override;
  void ShowStatusbar(bool show) override;
  void ShowToolPanel(bool show) override;
  int TabletGetCursor() override;

  // Note: Not an override, used directly by FaintWindow
  void TabletSetCursor(int tabletCursor);

  void ToggleFullScreen(bool) override;
  void ToggleMaximize() override;
  void UpdateShownSettings() override;
  void UpdateToolSettings(const Settings&) override;
  void SetTabCtrl(TabCtrl*); // Non virtual

private:
  FaintDialogContext m_dialogContext;
  FaintWindowExtraOverlay m_extraOverlay;
  FaintWindow& m_faintWindow;
  HelpFrame& m_helpFrame;
  FaintWindowInteraction m_interaction;
  InterpreterFrame& m_interpreterFrame;
  int m_modalDialog;
  SBInterface m_statusbar;
  Grid m_defaultGrid;
  ResizeDialogOptions m_defaultResizeSettings;
  TransparencyStyle m_transparencyStyle;
  int m_tabletCursor;
  dumb_ptr<TabCtrl> m_tabControl;
};

template<typename T>
void change_setting(FaintWindow& window,
  const T& setting,
  typename T::ValueType value,
  const from_control& fromControl,
  FaintDialogContext& dialogContext)
{
  dialogContext.ShownWindow().Visit(
    [&](CommandWindow& w){
      const auto& windowSettings(w.GetSettings());
      if (windowSettings.Has(setting)){
        // Fixme: Silly
        dialogContext.UpdateSettings(with(windowSettings, setting, value));
        // w.UpdateSettings(with(windowSettings, setting, value));
      }
    },
    [](){});

  Tool* tool = window.GetActiveTool();
  if (tool->GetSettings().Has(setting)){
    bool toolModified = tool->Set({setting, value});
    if (toolModified) {
      window.GetActiveCanvas().Refresh();
    }
    if (tool->EatsSettings()){
      if (!fromControl.Get()){
        window.UpdateShownSettings();
      }
      return;
    }
  }
  window.GetToolSettings().Set(setting, value);
  if (!fromControl.Get()){
    window.UpdateShownSettings();
  }
}

} // namespace

#endif
<|endoftext|>


<commit_before>/*  This file is part of Fabula.
    Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>

    Fabula is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Fabula is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Fabula. If not, see <http://www.gnu.org/licenses/>.
*/

#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "Database.h"
#include "TableTreeModel.h"
#include "TwoRowDelegate.h"
#include "PreferencesDialog.h"
#include "EventDialog.h"

#include <QFileDialog>
#include <QSqlRelationalTableModel>
#include <QTableView>
#include <QFile>
#include <QDebug>
#include <QSortFilterProxyModel>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    database(0),
    eventsModel(0),
    conversationsModel(0)
{
    ui->setupUi(this);

    QString fileName = settings.value("database").toString();

    if (fileName.isEmpty()) {
        newFile();
    }
    else {
        openFile(fileName);
    }

    ui->statusBar->hide();

    ui->splitter->setStretchFactor(1, 3);

    PreferencesDialog *preferences = new PreferencesDialog(this);
    EventDialog *eventDialog = new EventDialog(this);
    eventDialog->setModal(false);
    eventDialog->show();

    connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile()));
    connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile()));
    connect(ui->actionAdd_Event, SIGNAL(triggered()), this, SLOT(addEvent()));
    connect(ui->actionDelete_Event, SIGNAL(triggered()), this, SLOT(deleteEvent()));
    connect(ui->actionAdd_Conversation, SIGNAL(triggered()), this, SLOT(addToConversationTree()));
    connect(ui->actionDelete_Conversation, SIGNAL(triggered()), this, SLOT(removeFromConversationTree()));
    connect(ui->actionPreferences, SIGNAL(triggered()), preferences, SLOT(open()));

    connect(ui->conversationsView, SIGNAL(clicked(QModelIndex)),
            this, SLOT(filterOnConversation(QModelIndex)));

    eventsModel = new QSqlRelationalTableModel();
    eventsModel->setTable("events");
    eventsModel->setEditStrategy(QSqlTableModel::OnFieldChange);

    eventsModel->setHeaderData(0, Qt::Horizontal, tr("ID"));
    eventsModel->setHeaderData(1, Qt::Horizontal, tr("Type"));
    eventsModel->setRelation(1, QSqlRelation("event_types", "id", "name"));
    eventsModel->setHeaderData(2, Qt::Horizontal, tr("Conversation"));
    eventsModel->setRelation(2, QSqlRelation("conversations", "id", "name"));
    eventsModel->setHeaderData(3, Qt::Horizontal, tr("Character"));
    eventsModel->setRelation(3, QSqlRelation("characters", "id", "name"));
    eventsModel->setHeaderData(4, Qt::Horizontal, tr("Audio File"));
    eventsModel->setRelation(4, QSqlRelation("audiofiles", "id", "url"));
    eventsModel->setHeaderData(5, Qt::Horizontal, tr("Text"));

    eventsModel->select();

    ui->eventsView->setModel(eventsModel);
    ui->eventsView->hideColumn(0);
    ui->eventsView->horizontalHeader()->setStretchLastSection(true);
    ui->eventsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
    ui->eventsView->setWordWrap(true);
    ui->eventsView->setShowGrid(true);
    ui->eventsView->setAlternatingRowColors(true);

    QSqlRelationalDelegate *eventsDelegate = new QSqlRelationalDelegate(this);
    ui->eventsView->setItemDelegate(eventsDelegate);

    conversationsModel = new SqlTreeModel(this);
    ui->conversationsView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->conversationsView->setUniformRowHeights(true);
    ui->conversationsView->header()->setStretchLastSection(false);
    ui->conversationsView->header()->setResizeMode(QHeaderView::ResizeToContents);
    ui->conversationsView->setModel(conversationsModel);

    connect(conversationsModel, SIGNAL(submitted()), this, SLOT(reloadEvents()));
}

void MainWindow::newFile()
{
    QString fileName = QFileDialog::getSaveFileName(
            this, tr("New File"),
            desktopServices.storageLocation(QDesktopServices::DocumentsLocation),
            tr("Fabula Files (*.fabula)"));
    if (QFile::exists(fileName))
        QFile::remove(fileName);
    openFile(fileName);
}

void MainWindow::openFile(QString fileName)
{
    if (fileName.isEmpty()) {
        fileName = QFileDialog::getOpenFileName(
                this, tr("Open File"),
                desktopServices.storageLocation(QDesktopServices::DocumentsLocation),
                tr("Fabula Files (*.fabula)"));
    }
    if (!fileName.isEmpty()) {
        if (database) {
            delete database;
            database = 0;
        }
        database = new Database(fileName);
        settings.setValue("database", fileName);
        reloadEvents();
        if (conversationsModel)
            conversationsModel->reset();
        setWindowTitle(QString("%1 - Fabula").arg(fileName));
        ui->centralWidget->setEnabled(true);
    }
    else {
        if (!database) {
            ui->centralWidget->setEnabled(false);
        }
    }
}

void MainWindow::filterOnConversation(const QModelIndex& index)
{
    static const int conversationRow = 2;
    static const int characterRow = 3;

    if (!conversationsModel || !eventsModel)
        return;

    QString filter;
    int row = 0;
    if (index.parent().isValid())
        row = conversationRow;
    else
        row = characterRow;
    const QString name = conversationsModel->data(index).toString();
    // The "relTblAl_" is from the QSqlRelationalTableModel source.
    // This was needed as otherwise it's not obvious how to filter without breaking relations.
    filter = QString("relTblAl_%1.name='%2'").arg(row).arg(name);
    eventsModel->setFilter(filter);
}

void MainWindow::addEvent()
{
    eventsModel->insertRow(ui->eventsView->currentIndex().row()+1);
}

void MainWindow::deleteEvent()
{
    eventsModel->removeRow(ui->eventsView->currentIndex().row());
}

void MainWindow::addToConversationTree()
{
    conversationsModel->insertRow(ui->conversationsView->currentIndex().row(),
                                      ui->conversationsView->currentIndex().parent());
}

void MainWindow::removeFromConversationTree()
{
    conversationsModel->removeRow(ui->conversationsView->currentIndex().row(),
                                      ui->conversationsView->currentIndex().parent());
}

void MainWindow::reloadEvents()
{
    if (eventsModel)
        eventsModel->select();
    if (ui->conversationsView)
        filterOnConversation(ui->conversationsView->currentIndex());
}

MainWindow::~MainWindow()
{
    delete ui;
    // Delete here rather than using this object as parent so we can ensure the
    // database is deleted last.
    delete eventsModel;
    delete database;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
<commit_msg>Fix missing include compilation error.<commit_after>/*  This file is part of Fabula.
    Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>

    Fabula is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Fabula is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Fabula. If not, see <http://www.gnu.org/licenses/>.
*/

#include "MainWindow.h"
#include "ui_MainWindow.h"

#include "Database.h"
#include "TableTreeModel.h"
#include "PreferencesDialog.h"
#include "EventDialog.h"

#include <QFileDialog>
#include <QSqlRelationalTableModel>
#include <QTableView>
#include <QFile>
#include <QDebug>
#include <QSortFilterProxyModel>
#include <QSqlRelationalDelegate>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    database(0),
    eventsModel(0),
    conversationsModel(0)
{
    ui->setupUi(this);

    QString fileName = settings.value("database").toString();

    if (fileName.isEmpty()) {
        newFile();
    }
    else {
        openFile(fileName);
    }

    ui->statusBar->hide();

    ui->splitter->setStretchFactor(1, 3);

    PreferencesDialog *preferences = new PreferencesDialog(this);
    EventDialog *eventDialog = new EventDialog(this);
    eventDialog->setModal(false);
    eventDialog->show();

    connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile()));
    connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile()));
    connect(ui->actionAdd_Event, SIGNAL(triggered()), this, SLOT(addEvent()));
    connect(ui->actionDelete_Event, SIGNAL(triggered()), this, SLOT(deleteEvent()));
    connect(ui->actionAdd_Conversation, SIGNAL(triggered()), this, SLOT(addToConversationTree()));
    connect(ui->actionDelete_Conversation, SIGNAL(triggered()), this, SLOT(removeFromConversationTree()));
    connect(ui->actionPreferences, SIGNAL(triggered()), preferences, SLOT(open()));

    connect(ui->conversationsView, SIGNAL(clicked(QModelIndex)),
            this, SLOT(filterOnConversation(QModelIndex)));

    eventsModel = new QSqlRelationalTableModel();
    eventsModel->setTable("events");
    eventsModel->setEditStrategy(QSqlTableModel::OnFieldChange);

    eventsModel->setHeaderData(0, Qt::Horizontal, tr("ID"));
    eventsModel->setHeaderData(1, Qt::Horizontal, tr("Type"));
    eventsModel->setRelation(1, QSqlRelation("event_types", "id", "name"));
    eventsModel->setHeaderData(2, Qt::Horizontal, tr("Conversation"));
    eventsModel->setRelation(2, QSqlRelation("conversations", "id", "name"));
    eventsModel->setHeaderData(3, Qt::Horizontal, tr("Character"));
    eventsModel->setRelation(3, QSqlRelation("characters", "id", "name"));
    eventsModel->setHeaderData(4, Qt::Horizontal, tr("Audio File"));
    eventsModel->setRelation(4, QSqlRelation("audiofiles", "id", "url"));
    eventsModel->setHeaderData(5, Qt::Horizontal, tr("Text"));

    eventsModel->select();

    ui->eventsView->setModel(eventsModel);
    ui->eventsView->hideColumn(0);
    ui->eventsView->horizontalHeader()->setStretchLastSection(true);
    ui->eventsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
    ui->eventsView->setWordWrap(true);
    ui->eventsView->setShowGrid(true);
    ui->eventsView->setAlternatingRowColors(true);

    QSqlRelationalDelegate *eventsDelegate = new QSqlRelationalDelegate(this);
    ui->eventsView->setItemDelegate(eventsDelegate);

    conversationsModel = new SqlTreeModel(this);
    ui->conversationsView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->conversationsView->setUniformRowHeights(true);
    ui->conversationsView->header()->setStretchLastSection(false);
    ui->conversationsView->header()->setResizeMode(QHeaderView::ResizeToContents);
    ui->conversationsView->setModel(conversationsModel);

    connect(conversationsModel, SIGNAL(submitted()), this, SLOT(reloadEvents()));
}

void MainWindow::newFile()
{
    QString fileName = QFileDialog::getSaveFileName(
            this, tr("New File"),
            desktopServices.storageLocation(QDesktopServices::DocumentsLocation),
            tr("Fabula Files (*.fabula)"));
    if (QFile::exists(fileName))
        QFile::remove(fileName);
    openFile(fileName);
}

void MainWindow::openFile(QString fileName)
{
    if (fileName.isEmpty()) {
        fileName = QFileDialog::getOpenFileName(
                this, tr("Open File"),
                desktopServices.storageLocation(QDesktopServices::DocumentsLocation),
                tr("Fabula Files (*.fabula)"));
    }
    if (!fileName.isEmpty()) {
        if (database) {
            delete database;
            database = 0;
        }
        database = new Database(fileName);
        settings.setValue("database", fileName);
        reloadEvents();
        if (conversationsModel)
            conversationsModel->reset();
        setWindowTitle(QString("%1 - Fabula").arg(fileName));
        ui->centralWidget->setEnabled(true);
    }
    else {
        if (!database) {
            ui->centralWidget->setEnabled(false);
        }
    }
}

void MainWindow::filterOnConversation(const QModelIndex& index)
{
    static const int conversationRow = 2;
    static const int characterRow = 3;

    if (!conversationsModel || !eventsModel)
        return;

    QString filter;
    int row = 0;
    if (index.parent().isValid())
        row = conversationRow;
    else
        row = characterRow;
    const QString name = conversationsModel->data(index).toString();
    // The "relTblAl_" is from the QSqlRelationalTableModel source.
    // This was needed as otherwise it's not obvious how to filter without breaking relations.
    filter = QString("relTblAl_%1.name='%2'").arg(row).arg(name);
    eventsModel->setFilter(filter);
}

void MainWindow::addEvent()
{
    eventsModel->insertRow(ui->eventsView->currentIndex().row()+1);
}

void MainWindow::deleteEvent()
{
    eventsModel->removeRow(ui->eventsView->currentIndex().row());
}

void MainWindow::addToConversationTree()
{
    conversationsModel->insertRow(ui->conversationsView->currentIndex().row(),
                                      ui->conversationsView->currentIndex().parent());
}

void MainWindow::removeFromConversationTree()
{
    conversationsModel->removeRow(ui->conversationsView->currentIndex().row(),
                                      ui->conversationsView->currentIndex().parent());
}

void MainWindow::reloadEvents()
{
    if (eventsModel)
        eventsModel->select();
    if (ui->conversationsView)
        filterOnConversation(ui->conversationsView->currentIndex());
}

MainWindow::~MainWindow()
{
    delete ui;
    // Delete here rather than using this object as parent so we can ensure the
    // database is deleted last.
    delete eventsModel;
    delete database;
}

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


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#include    "../../../Foundation/Characters/String_Constant.h"
#include    "../../../Foundation/Characters/String2Float.h"
#include    "../../../Foundation/Characters/String2Int.h"
#include    "../../../Foundation/Containers/Mapping.h"
#include    "../../../Foundation/Containers/Sequence.h"
#include    "../../../Foundation/Containers/Set.h"
#include    "../../../Foundation/Debug/Assertions.h"
#include    "../../../Foundation/Debug/Trace.h"
#include    "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h"
#include    "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include    "../../../Foundation/Streams/BinaryInputStream.h"

#include    "../CommonMeasurementTypes.h"

#include    "Memory.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::DataExchange;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;

using   Characters::Character;
using   Characters::String_Constant;
using   Containers::Mapping;
using   Containers::Sequence;
using   Containers::Set;
using   IO::FileSystem::BinaryFileInputStream;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

namespace {
    template <typename T>
    void    ReadMemInfoLine_ (Optional<T>* result, const String& n, const Sequence<String>& line)
    {
        if (line.size () >= 3 and line[0] == n) {
            String  unit = line[2];
            double  factor = (unit == L"kB") ? 1024 : 1;
            *result = static_cast<T> (round (Characters::String2Float<double> (line[1]) * factor));
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result));
#endif
        }
    }
    template <typename T>
    void    ReadVMStatLine_ (Optional<T>* result, const String& n, const Sequence<String>& line)
    {
        if (line.size () >= 2 and line[0] == n) {
            *result = Characters::String2Int<T> (line[1]);
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result));
#endif
        }
    }
    Instruments::Memory::Info capture_ ()
    {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
        Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture_");
#endif

        constexpr   bool    kManuallyComputePagesPerSecond_ { true };

        Instruments::Memory::Info   result;
#if     qPlatform_POSIX
        {
            DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }};
            const   String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" };
            //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" };
            // Note - /procfs files always unseekable
            for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcMemInfoFileName_, BinaryFileInputStream::eNotSeekable))) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
                DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
                ReadMemInfoLine_ (&result.fFreePhysicalMemory, String_Constant (L"MemFree"), line);
                ReadMemInfoLine_ (&result.fTotalVirtualMemory, String_Constant (L"VmallocTotal"), line);
                ReadMemInfoLine_ (&result.fUsedVirtualMemory, String_Constant (L"VmallocUsed"), line);
                ReadMemInfoLine_ (&result.fLargestAvailableVirtualChunk, String_Constant (L"VmallocChunk"), line);
            }
        }
        {
            DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }};
            const   String_Constant kProcVMStatFileName_ { L"/proc/vmstat" };
            Optional<uint64_t>  pgfault;
            // Note - /procfs files always unseekable
            for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcVMStatFileName_, BinaryFileInputStream::eNotSeekable))) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
                DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
                ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line);
                ReadVMStatLine_ (&result.fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line);
            }
            if (pgfault.IsPresent () and result.fMajorPageFaultsSinceBoot.IsPresent ()) {
                result.fMinorPageFaultsSinceBoot = *pgfault - *result.fMajorPageFaultsSinceBoot;
            }
        }
#elif   qPlatform_Windows
#endif
        if (kManuallyComputePagesPerSecond_) {
            static  mutex                       s_Mutex_;
            static  uint64_t                    s_Saved_MajorPageFaultsSinceBoot {};
            static  Time::DurationSecondsType   s_Saved_MajorPageFaultsSinceBoot_At {};
            if (result.fMajorPageFaultsSinceBoot.IsPresent ()) {
                Time::DurationSecondsType   now = Time::GetTickCount ();
                auto    critSec { Execution::make_unique_lock (s_Mutex_) };
                if (s_Saved_MajorPageFaultsSinceBoot_At != 0) {
                    result.fMajorPageFaultsPerSecond = (*result.fMajorPageFaultsSinceBoot - s_Saved_MajorPageFaultsSinceBoot) / (now - s_Saved_MajorPageFaultsSinceBoot_At);
                }
                s_Saved_MajorPageFaultsSinceBoot = *result.fMajorPageFaultsSinceBoot;
                s_Saved_MajorPageFaultsSinceBoot_At = now;
            }
        }
        return result;
    }
}

const   MeasurementType Instruments::Memory::kSystemMemoryMeasurement = MeasurementType (String_Constant (L"System-Memory"));

/*
 ********************************************************************************
 ******************** Instruments::Memory::GetObjectVariantMapper ***************
 ********************************************************************************
 */
ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper ()
{
    using   StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
    ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
        ObjectVariantMapper mapper;
        mapper.AddCommonType<Optional<uint64_t>> ();
        mapper.AddCommonType<Optional<double>> ();
        DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\"");   // Really probably an issue, but not to debug here -- LGP 2014-01-04
        DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\"");       // Really probably an issue, but not to debug here -- LGP 2014-01-04
        mapper.AddClass<Info> (initializer_list<StructureFieldInfo> {
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L"Free-Physical-Memory") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalVirtualMemory), String_Constant (L"Total-Virtual-Memory") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fUsedVirtualMemory), String_Constant (L"UsedV-irtual-Memory") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L"Largest-Available-Virtual-Chunk") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Page-Faults-Since-Boot") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Page-Faults-Since-Boot") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L"Major-Page-Faults-Per-Second") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Page-Faults-Per-Second") },
        });
        DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
        DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
        return mapper;
    } ();
    return sMapper_;
}

/*
 ********************************************************************************
 ******************* Instruments::Memory::GetInstrument *************************
 ********************************************************************************
 */
Instrument  SystemPerformance::Instruments::Memory::GetInstrument ()
{
    static  Instrument  kInstrument_    = Instrument (
            InstrumentNameType (String_Constant (L"Memory")),
    [] () -> MeasurementSet {
        MeasurementSet    results;
        DateTime    before = DateTime::Now ();
        Instruments::Memory::Info rawMeasurement = capture_ ();
        results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
        Measurement m;
        m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
        m.fType = kSystemMemoryMeasurement;
        results.fMeasurements.Add (m);
        return results;
    },
    {kMemoryUsage},
    GetObjectVariantMapper ()
                                          );
    return kInstrument_;
}
<commit_msg>Refactor systemperofrmacne instrumewnt to use capture pattern, and got windows memory capture stats working (at least well enuf for frictionscanner)<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#include    "../../../Foundation/Characters/String_Constant.h"
#include    "../../../Foundation/Characters/String2Float.h"
#include    "../../../Foundation/Characters/String2Int.h"
#include    "../../../Foundation/Containers/Mapping.h"
#include    "../../../Foundation/Containers/Sequence.h"
#include    "../../../Foundation/Containers/Set.h"
#include    "../../../Foundation/Debug/Assertions.h"
#include    "../../../Foundation/Debug/Trace.h"
#include    "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h"
#include    "../../../Foundation/Execution/Sleep.h"
#include    "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include    "../../../Foundation/Streams/BinaryInputStream.h"

#include    "../CommonMeasurementTypes.h"

#include    "Memory.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::DataExchange;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;

using   Characters::Character;
using   Characters::String_Constant;
using   Containers::Mapping;
using   Containers::Sequence;
using   Containers::Set;
using   IO::FileSystem::BinaryFileInputStream;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#ifndef qUseWMICollectionSupport_
#define qUseWMICollectionSupport_       qPlatform_Windows
#endif

#if     qUseWMICollectionSupport_
#include    "../Support/WMICollector.h"

using   SystemPerformance::Support::WMICollector;
#endif

namespace {
#if     qUseWMICollectionSupport_
    const   String_Constant     kCommittedBytes_    { L"Committed Bytes" };
    const   String_Constant     kCommitLimit_       { L"Commit Limit" };
    const   String_Constant     kPagesPerSec_       { L"Pages/sec" };           // hard page faults/sec
#endif
}

namespace {
    template <typename T>
    void    ReadMemInfoLine_ (Optional<T>* result, const String& n, const Sequence<String>& line)
    {
        if (line.size () >= 3 and line[0] == n) {
            String  unit = line[2];
            double  factor = (unit == L"kB") ? 1024 : 1;
            *result = static_cast<T> (round (Characters::String2Float<double> (line[1]) * factor));
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result));
#endif
        }
    }
    template <typename T>
    void    ReadVMStatLine_ (Optional<T>* result, const String& n, const Sequence<String>& line)
    {
        if (line.size () >= 2 and line[0] == n) {
            *result = Characters::String2Int<T> (line[1]);
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result));
#endif
        }
    }
}

namespace {
    struct  CapturerWithContext_ {
#if     qUseWMICollectionSupport_
        WMICollector    fMemoryWMICollector_ { L"Memory", {L"_Total"},  {kCommittedBytes_, kCommitLimit_, kPagesPerSec_ } };
#endif
        CapturerWithContext_ ()
        {
#if     qUseWMICollectionSupport_
            fMemoryWMICollector_.Collect ();
            {
                const Time::DurationSecondsType kUseIntervalIfNoBaseline_ { 1.0 };
                Execution::Sleep (kUseIntervalIfNoBaseline_);
            }
#endif
        }
        CapturerWithContext_ (const CapturerWithContext_& from)
#if     qUseWMICollectionSupport_
            : fMemoryWMICollector_ (from.fMemoryWMICollector_)
#endif
        {
#if   qUseWMICollectionSupport_
            fMemoryWMICollector_.Collect ();
            {
                const Time::DurationSecondsType kUseIntervalIfNoBaseline_ { 1.0 };
                Execution::Sleep (kUseIntervalIfNoBaseline_);
            }
#endif
        }
        Instruments::Memory::Info capture_ ()
        {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture_");
#endif

            constexpr   bool    kManuallyComputePagesPerSecond_ { true };

            Instruments::Memory::Info   result;
#if     qPlatform_POSIX
            {
                DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }};
                const   String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" };
                //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" };
                // Note - /procfs files always unseekable
                for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcMemInfoFileName_, BinaryFileInputStream::eNotSeekable))) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
                    DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
                    ReadMemInfoLine_ (&result.fFreePhysicalMemory, String_Constant (L"MemFree"), line);
                    ReadMemInfoLine_ (&result.fTotalVirtualMemory, String_Constant (L"VmallocTotal"), line);
                    ReadMemInfoLine_ (&result.fUsedVirtualMemory, String_Constant (L"VmallocUsed"), line);
                    ReadMemInfoLine_ (&result.fLargestAvailableVirtualChunk, String_Constant (L"VmallocChunk"), line);
                }
            }
            {
                DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }};
                const   String_Constant kProcVMStatFileName_ { L"/proc/vmstat" };
                Optional<uint64_t>  pgfault;
                // Note - /procfs files always unseekable
                for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcVMStatFileName_, BinaryFileInputStream::eNotSeekable))) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
                    DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
                    ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line);
                    ReadVMStatLine_ (&result.fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line);
                }
                if (pgfault.IsPresent () and result.fMajorPageFaultsSinceBoot.IsPresent ()) {
                    result.fMinorPageFaultsSinceBoot = *pgfault - *result.fMajorPageFaultsSinceBoot;
                }
            }
#elif   qPlatform_Windows
#if     qUseWMICollectionSupport_
            fMemoryWMICollector_.Collect ();
            {
                if (auto o = fMemoryWMICollector_.PeekCurrentValue (L"_Total", kCommittedBytes_)) {
                    result.fUsedVirtualMemory = *o ;
                }
                if (auto o = fMemoryWMICollector_.PeekCurrentValue (L"_Total", kCommitLimit_)) {
                    // bad names - RETHINK
                    result.fTotalVirtualMemory = *o ;
                }
                if (auto o = fMemoryWMICollector_.PeekCurrentValue (L"_Total", kPagesPerSec_)) {
                    result.fMajorPageFaultsPerSecond = *o ;
                }
            }
#endif
            {
                MEMORYSTATUSEX statex;
                statex.dwLength = sizeof (statex);
                Verify (::GlobalMemoryStatusEx (&statex) != 0);
                result.fFreePhysicalMemory = statex.ullAvailPhys;
            }
#endif
            if (kManuallyComputePagesPerSecond_) {
                static  mutex                       s_Mutex_;
                static  uint64_t                    s_Saved_MajorPageFaultsSinceBoot {};
                static  Time::DurationSecondsType   s_Saved_MajorPageFaultsSinceBoot_At {};
                if (result.fMajorPageFaultsSinceBoot.IsPresent ()) {
                    Time::DurationSecondsType   now = Time::GetTickCount ();
                    auto    critSec { Execution::make_unique_lock (s_Mutex_) };
                    if (s_Saved_MajorPageFaultsSinceBoot_At != 0) {
                        result.fMajorPageFaultsPerSecond = (*result.fMajorPageFaultsSinceBoot - s_Saved_MajorPageFaultsSinceBoot) / (now - s_Saved_MajorPageFaultsSinceBoot_At);
                    }
                    s_Saved_MajorPageFaultsSinceBoot = *result.fMajorPageFaultsSinceBoot;
                    s_Saved_MajorPageFaultsSinceBoot_At = now;
                }
            }
            return result;
        }
    };
}

const   MeasurementType Instruments::Memory::kSystemMemoryMeasurement = MeasurementType (String_Constant (L"System-Memory"));

/*
 ********************************************************************************
 ******************** Instruments::Memory::GetObjectVariantMapper ***************
 ********************************************************************************
 */
ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper ()
{
    using   StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
    ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
        ObjectVariantMapper mapper;
        mapper.AddCommonType<Optional<uint64_t>> ();
        mapper.AddCommonType<Optional<double>> ();
        DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\"");   // Really probably an issue, but not to debug here -- LGP 2014-01-04
        DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\"");       // Really probably an issue, but not to debug here -- LGP 2014-01-04
        mapper.AddClass<Info> (initializer_list<StructureFieldInfo> {
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L"Free-Physical-Memory") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalVirtualMemory), String_Constant (L"Total-Virtual-Memory") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fUsedVirtualMemory), String_Constant (L"UsedV-irtual-Memory") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L"Largest-Available-Virtual-Chunk") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Page-Faults-Since-Boot") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Page-Faults-Since-Boot") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L"Major-Page-Faults-Per-Second") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Page-Faults-Per-Second") },
        });
        DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
        DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
        return mapper;
    } ();
    return sMapper_;
}

/*
 ********************************************************************************
 ******************* Instruments::Memory::GetInstrument *************************
 ********************************************************************************
 */
Instrument  SystemPerformance::Instruments::Memory::GetInstrument ()
{
    CapturerWithContext_ useCaptureContext;  // capture context so copyable in mutable lambda
    static  Instrument  kInstrument_    = Instrument (
            InstrumentNameType (String_Constant (L"Memory")),
    [useCaptureContext] () mutable -> MeasurementSet {
        MeasurementSet    results;
        DateTime    before = DateTime::Now ();
        Instruments::Memory::Info rawMeasurement = useCaptureContext.capture_ ();
        results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
        Measurement m;
        m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
        m.fType = kSystemMemoryMeasurement;
        results.fMeasurements.Add (m);
        return results;
    },
    {kMemoryUsage},
    GetObjectVariantMapper ()
                                          );
    return kInstrument_;
}
<|endoftext|>


<commit_before>//Author: Stefan Toman

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <map>
#include <math.h>

using namespace std;

int main() {
	int t;
	scanf("%d", &t);
	for (int i = 0; i < t; ++i) {
        long n, p;
		scanf("%ld %ld", &n, &p);
		long b[n];
		for (long j = 0; j < n; j++) {
			scanf("%ld", &b[j]);
		}
		long long r = 0;
		long right = -1, sum = 0;
		for (long left = 0; left < n && right < n; left++) {
			while(right+1 < n && sum + b[right+1] <= p) {
				sum += b[right+1];
				right++;
			}
			r += right - left + 1;
			sum -= b[left];
		}
		printf("Case #%d: %I64d\n", i+1, r);
	}
	return 0;
}
<commit_msg>fix problem thepriceiscorrect<commit_after>//Author: Stefan Toman

#include <iostream>
#include <string.h>
#include <algorithm>
#include <map>
#include <math.h>

using namespace std;

int main() {
	int t;
	cin >> t;
	for (int i = 0; i < t; ++i) {
        long n, p;
		cin >> n >> p;
		long b[n];
		for (long j = 0; j < n; j++) {
			cin >> b[j];
		}
		long long r = 0;
		long right = -1, sum = 0;
		for (long left = 0; left < n && right < n; left++) {
			while(right+1 < n && sum + b[right+1] <= p) {
				sum += b[right+1];
				right++;
			}
			r += right - left + 1;
			sum -= b[left];
		}
		cout << "Case #" << i+1 << ": " << r << endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>/*
* Montgomery Exponentiation
* (C) 1999-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/internal/def_powm.h>
#include <botan/numthry.h>
#include <botan/internal/mp_core.h>

namespace Botan {

/*
* Set the exponent
*/
void Montgomery_Exponentiator::set_exponent(const BigInt& exp)
   {
   this->exp = exp;
   exp_bits = exp.bits();
   }

/*
* Set the base
*/
void Montgomery_Exponentiator::set_base(const BigInt& base)
   {
   window_bits = Power_Mod::window_bits(exp.bits(), base.bits(), hints);

   g.resize((1 << window_bits) - 1);

   SecureVector<word> z(2 * (mod_words + 1));
   SecureVector<word> workspace(z.size());

   g[0] = (base >= modulus) ? (base % modulus) : base;

   bigint_monty_mul(&z[0], z.size(),
                    g[0].data(), g[0].size(), g[0].sig_words(),
                    R2.data(), R2.size(), R2.sig_words(),
                    modulus.data(), mod_words, mod_prime,
                    &workspace[0]);

   g[0].assign(&z[0], mod_words + 1);

   const BigInt& x = g[0];
   const size_t x_sig = x.sig_words();

   for(size_t i = 1; i != g.size(); ++i)
      {
      const BigInt& y = g[i-1];
      const size_t y_sig = y.sig_words();

      zeroise(z);
      bigint_monty_mul(&z[0], z.size(),
                       x.data(), x.size(), x_sig,
                       y.data(), y.size(), y_sig,
                       modulus.data(), mod_words, mod_prime,
                       &workspace[0]);

      g[i].assign(&z[0], mod_words + 1);
      }
   }

/*
* Compute the result
*/
BigInt Montgomery_Exponentiator::execute() const
   {
   const size_t exp_nibbles = (exp_bits + window_bits - 1) / window_bits;

   BigInt x = R_mod;
   SecureVector<word> z(2 * (mod_words + 1));
   SecureVector<word> workspace(2 * (mod_words + 1));

   for(size_t i = exp_nibbles; i > 0; --i)
      {
      for(size_t k = 0; k != window_bits; ++k)
         {
         zeroise(z);

         bigint_monty_sqr(&z[0], z.size(),
                          x.data(), x.size(), x.sig_words(),
                          modulus.data(), mod_words, mod_prime,
                          &workspace[0]);

         x.assign(&z[0], mod_words + 1);
         }

      if(u32bit nibble = exp.get_substring(window_bits*(i-1), window_bits))
         {
         const BigInt& y = g[nibble-1];

         zeroise(z);
         bigint_monty_mul(&z[0], z.size(),
                          x.data(), x.size(), x.sig_words(),
                          y.data(), y.size(), y.sig_words(),
                          modulus.data(), mod_words, mod_prime,
                          &workspace[0]);

         x.assign(&z[0], mod_words + 1);
         }
      }

   x.get_reg().resize(2*mod_words+1);

   bigint_monty_redc(&x[0], x.size(),
                     modulus.data(), mod_words, mod_prime,
                     &workspace[0]);

   x.get_reg().resize(mod_words+1);

   return x;
   }

/*
* Montgomery_Exponentiator Constructor
*/
Montgomery_Exponentiator::Montgomery_Exponentiator(const BigInt& mod,
   Power_Mod::Usage_Hints hints)
   {
   // Montgomery reduction only works for positive odd moduli
   if(!mod.is_positive() || mod.is_even())
      throw Invalid_Argument("Montgomery_Exponentiator: invalid modulus");

   window_bits = 0;
   this->hints = hints;
   modulus = mod;

   mod_words = modulus.sig_words();

   BigInt mod_prime_bn(BigInt::Power2, MP_WORD_BITS);
   mod_prime = (mod_prime_bn - inverse_mod(modulus, mod_prime_bn)).word_at(0);

   R_mod = BigInt(BigInt::Power2, MP_WORD_BITS * mod_words);
   R_mod %= modulus;

   R2 = BigInt(BigInt::Power2, 2 * MP_WORD_BITS * mod_words);
   R2 %= modulus;
   }

}
<commit_msg>Simplify Montgomery setup here a bit<commit_after>/*
* Montgomery Exponentiation
* (C) 1999-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/internal/def_powm.h>
#include <botan/numthry.h>
#include <botan/internal/mp_core.h>

namespace Botan {

/*
* Set the exponent
*/
void Montgomery_Exponentiator::set_exponent(const BigInt& exp)
   {
   this->exp = exp;
   exp_bits = exp.bits();
   }

/*
* Set the base
*/
void Montgomery_Exponentiator::set_base(const BigInt& base)
   {
   window_bits = Power_Mod::window_bits(exp.bits(), base.bits(), hints);

   g.resize((1 << window_bits) - 1);

   SecureVector<word> z(2 * (mod_words + 1));
   SecureVector<word> workspace(z.size());

   g[0] = (base >= modulus) ? (base % modulus) : base;

   bigint_monty_mul(&z[0], z.size(),
                    g[0].data(), g[0].size(), g[0].sig_words(),
                    R2.data(), R2.size(), R2.sig_words(),
                    modulus.data(), mod_words, mod_prime,
                    &workspace[0]);

   g[0].assign(&z[0], mod_words + 1);

   const BigInt& x = g[0];
   const size_t x_sig = x.sig_words();

   for(size_t i = 1; i != g.size(); ++i)
      {
      const BigInt& y = g[i-1];
      const size_t y_sig = y.sig_words();

      zeroise(z);
      bigint_monty_mul(&z[0], z.size(),
                       x.data(), x.size(), x_sig,
                       y.data(), y.size(), y_sig,
                       modulus.data(), mod_words, mod_prime,
                       &workspace[0]);

      g[i].assign(&z[0], mod_words + 1);
      }
   }

/*
* Compute the result
*/
BigInt Montgomery_Exponentiator::execute() const
   {
   const size_t exp_nibbles = (exp_bits + window_bits - 1) / window_bits;

   BigInt x = R_mod;
   SecureVector<word> z(2 * (mod_words + 1));
   SecureVector<word> workspace(2 * (mod_words + 1));

   for(size_t i = exp_nibbles; i > 0; --i)
      {
      for(size_t k = 0; k != window_bits; ++k)
         {
         zeroise(z);

         bigint_monty_sqr(&z[0], z.size(),
                          x.data(), x.size(), x.sig_words(),
                          modulus.data(), mod_words, mod_prime,
                          &workspace[0]);

         x.assign(&z[0], mod_words + 1);
         }

      if(u32bit nibble = exp.get_substring(window_bits*(i-1), window_bits))
         {
         const BigInt& y = g[nibble-1];

         zeroise(z);
         bigint_monty_mul(&z[0], z.size(),
                          x.data(), x.size(), x.sig_words(),
                          y.data(), y.size(), y.sig_words(),
                          modulus.data(), mod_words, mod_prime,
                          &workspace[0]);

         x.assign(&z[0], mod_words + 1);
         }
      }

   x.get_reg().resize(2*mod_words+1);

   bigint_monty_redc(&x[0], x.size(),
                     modulus.data(), mod_words, mod_prime,
                     &workspace[0]);

   x.get_reg().resize(mod_words+1);

   return x;
   }

/*
* Montgomery_Exponentiator Constructor
*/
Montgomery_Exponentiator::Montgomery_Exponentiator(const BigInt& mod,
   Power_Mod::Usage_Hints hints)
   {
   // Montgomery reduction only works for positive odd moduli
   if(!mod.is_positive() || mod.is_even())
      throw Invalid_Argument("Montgomery_Exponentiator: invalid modulus");

   window_bits = 0;
   this->hints = hints;
   modulus = mod;

   mod_words = modulus.sig_words();

   BigInt r(BigInt::Power2, mod_words * BOTAN_MP_WORD_BITS);
   mod_prime = (((r * inverse_mod(r, mod)) - 1) / mod).word_at(0);

   R_mod = r % modulus;

   R2 = (R_mod * R_mod) % modulus;
   }

}
<|endoftext|>


<commit_before>/*    Copyright (c) 2010-2015, Delft University of Technology
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without modification, are
 *    permitted provided that the following conditions are met:
 *      - Redistributions of source code must retain the above copyright notice, this list of
 *        conditions and the following disclaimer.
 *      - Redistributions in binary form must reproduce the above copyright notice, this list of
 *        conditions and the following disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *      - Neither the name of the Delft University of Technology nor the names of its contributors
 *        may be used to endorse or promote products derived from this software without specific
 *        prior written permission.
 *
 *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *    OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      121123    D. Dirkx          File created.
 *      130124    K. Kumar          Added missing file header; updated layout; migrated force
 *                                  free function to separate file; added acceleration free
 *                                  function.
 *
 *    References
 *
 *    Notes
 *
 */

#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"

#include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureAcceleration.h"
#include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureForce.h"

#include <cmath>

#include <vector>
#include <Eigen/Core>

namespace tudat
{
namespace electro_magnetism
{

//! Compute radiation pressure acceleration using an ideal sail model.

Eigen::Vector3d computeIdealRadiationPressureAcceleration(const double radiationPressure,
        const Eigen::Vector3d& normalFromSource,
        const Eigen::Vector3d& normalToSail,
        const double area,
        const double radiationPressureCoefficient,
        const double mass )
{
    return computeIdealRadiationPressureForce(
                radiationPressure, normalToSail,  normalFromSource, area, radiationPressureCoefficient - 1.0 ) / mass;;
}

} // namespace electro_magnetism
} // namespace tudat
<commit_msg>minor corrections<commit_after>/*    Copyright (c) 2010-2015, Delft University of Technology
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without modification, are
 *    permitted provided that the following conditions are met:
 *      - Redistributions of source code must retain the above copyright notice, this list of
 *        conditions and the following disclaimer.
 *      - Redistributions in binary form must reproduce the above copyright notice, this list of
 *        conditions and the following disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *      - Neither the name of the Delft University of Technology nor the names of its contributors
 *        may be used to endorse or promote products derived from this software without specific
 *        prior written permission.
 *
 *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *    OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *    Changelog
 *      YYMMDD    Author            Comment
 *      121123    D. Dirkx          File created.
 *      130124    K. Kumar          Added missing file header; updated layout; migrated force
 *                                  free function to separate file; added acceleration free
 *                                  function.
 *
 *    References
 *
 *    Notes
 *
 */

#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"

#include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureAcceleration.h"
#include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureForce.h"

#include <cmath>

#include <vector>
#include <Eigen/Core>

namespace tudat
{
namespace electro_magnetism
{

//! Compute radiation pressure acceleration using an ideal sail model.

Eigen::Vector3d computeIdealRadiationPressureAcceleration(
        const double radiationPressure,
        const Eigen::Vector3d& vectorFromSource,
        const Eigen::Vector3d& normalToSail,
        const double area,
        const double radiationPressureCoefficient,
        const double mass )
{
    return computeIdealRadiationPressureForce(
                radiationPressure, normalToSail,  vectorFromSource, area, radiationPressureCoefficient - 1.0 ) / mass;;
}

} // namespace electro_magnetism
} // namespace tudat
<|endoftext|>


<commit_before>/**
 * @file backtrace.cpp
 * @author Grzegorz Krajewski
 *
 * Implementation of the Backtrace class.
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */

#include <sstream>

#ifdef HAS_BFD_DL
  #include <execinfo.h>
  #include <signal.h>
  #include <unistd.h>
  #include <cxxabi.h>
  #ifndef PACKAGE
    #define PACKAGE
    #ifndef PACKAGE_VERSION
      #define PACKAGE_VERSION
      #include <bfd.h>
      #undef PACKAGE_VERSION
    #else
      #include <bfd.h>
    #endif
    #undef PACKAGE
  #else
    #ifndef PACKAGE_VERSION
      #define PACKAGE_VERSION
      #include <bfd.h>
      #undef PACKAGE_VERSION
    #else
      #include <bfd.h>
    #endif
  #endif
  #include <dlfcn.h>
#endif

#include "prefixedoutstream.hpp"
#include "backtrace.hpp"
#include "log.hpp"

// Easier to read Backtrace::DecodeAddress().
#ifdef HAS_BFD_DL
  #define TRACE_CONDITION_1 (!dladdr(trace[i], &addressHandler))
  #define FIND_LINE (bfd_find_nearest_line(abfd, text, syms, offset, &frame.file, &frame.function, &frame.line) && frame.file)
#endif

using namespace mlpack;

// Initialize Backtrace static inctances.
Backtrace::Frames Backtrace::frame;
std::vector<Backtrace::Frames> Backtrace::stack;

#ifdef HAS_BFD_DL
// Binary File Descriptor objects.
bfd* abfd = 0;		// Descriptor datastructure.
asymbol **syms = 0;	// Symbols datastructure.
asection *text = 0;	// Strings datastructure.
#endif

#ifdef HAS_BFD_DL
Backtrace::Backtrace(int maxDepth)
{
  frame.address = NULL;
  frame.function = "0";
  frame.file = "0";
  frame.line = 0;

  stack.clear();

  GetAddress(maxDepth);
}
#else
Backtrace::Backtrace()
{
  // Dummy constructor
}
#endif

#ifdef HAS_BFD_DL
void Backtrace::GetAddress(int maxDepth)
{
  void* trace[maxDepth];
  int stackDepth = backtrace(trace, maxDepth);

  // Skip first stack frame (points to Backtrace::Backtrace).
  for (int i = 1; i < stackDepth; i++)
  {
    Dl_info addressHandler;

    //No backtrace will be printed if no compile flags: -g -rdynamic
    if(TRACE_CONDITION_1)
    {
      return ;
    }

    frame.address = addressHandler.dli_saddr;

    DecodeAddress((long)frame.address);
  }
}

void Backtrace::DecodeAddress(long addr)
{
  // Check to see if there is anything to descript. If it doesn't, we'll
  // dump running program.
  if (!abfd)
  {
    char ename[1024];
    int l = readlink("/proc/self/exe",ename,sizeof(ename));
    if (l == -1)
    {
      perror("Failed to open executable!\n");
      return;
    }
    ename[l] = 0;

    bfd_init();

    abfd = bfd_openr(ename, 0);
    if (!abfd)
    {
      perror("bfd_openr failed: ");
      return;
    }

    bfd_check_format(abfd,bfd_object);

    unsigned storage_needed = bfd_get_symtab_upper_bound(abfd);
    syms = (asymbol **) malloc(storage_needed);

    text = bfd_get_section_by_name(abfd, ".text");
   }

  long offset = addr - text->vma;

  if (offset > 0)
  {
    if(FIND_LINE)
    {
      DemangleFunction();
      // Save retrieved informations.
      stack.push_back(frame);
    }
  }
}

void Backtrace::DemangleFunction()
{
  int status;
  char* tmp = abi::__cxa_demangle(frame.function, 0, 0, &status);

  // If demangling is successful, reallocate 'frame.function' pointer to
  // demangled name. Else if 'status != 0', leave 'frame.function as it is.
  if (status == 0)
  {
    frame.function = tmp;
  }
}
#else
void Backtrace::GetAddress(int /* maxDepth */) { }
void Backtrace::DecodeAddress(long /* address */) { }
void Backtrace::DemangleFunction() { }
#endif

std::string Backtrace::ToString()
{
  std::string stackStr;

#ifdef HAS_BFD_DL
  std::ostringstream lineOss;
  std::ostringstream it;

  if(stack.size() <= 0)
  {
    stackStr = "Cannot give backtrace because program was compiled";
    stackStr += " without: -g -rdynamic\nFor a backtrace,";
    stackStr += " recompile with: -g -rdynamic.\n";

    return stackStr;
  }

  for(unsigned int i = 0; i < stack.size(); i++)
  {
    frame = stack[i];

    lineOss << frame.line;
    it << i + 1;

      stackStr += "[bt]: (" + it.str() + ") "
	       + frame.file + ":"
	       + lineOss.str() + " "
	       + frame.function + ":\n";

    lineOss.str("");
    it.str("");
  }
#else
  stackStr = "[bt]: No backtrace for this OS. Work in progress.";
#endif

  return stackStr;
}
<commit_msg>Add comment describing the need for setting PACKAGE and PACKAGE_VERSION.<commit_after>/**
 * @file backtrace.cpp
 * @author Grzegorz Krajewski
 *
 * Implementation of the Backtrace class.
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#include <sstream>

#ifdef HAS_BFD_DL
  #include <execinfo.h>
  #include <signal.h>
  #include <unistd.h>
  #include <cxxabi.h>

  // Some versions of libbfd require PACKAGE and PACKAGE_VERSION to be set in
  // order for the include to not fail.  For more information:
  // https://github.com/mlpack/mlpack/issues/574
  #ifndef PACKAGE
    #define PACKAGE
    #ifndef PACKAGE_VERSION
      #define PACKAGE_VERSION
      #include <bfd.h>
      #undef PACKAGE_VERSION
    #else
      #include <bfd.h>
    #endif
    #undef PACKAGE
  #else
    #ifndef PACKAGE_VERSION
      #define PACKAGE_VERSION
      #include <bfd.h>
      #undef PACKAGE_VERSION
    #else
      #include <bfd.h>
    #endif
  #endif
  #include <dlfcn.h>
#endif

#include "prefixedoutstream.hpp"
#include "backtrace.hpp"
#include "log.hpp"

// Easier to read Backtrace::DecodeAddress().
#ifdef HAS_BFD_DL
  #define TRACE_CONDITION_1 (!dladdr(trace[i], &addressHandler))
  #define FIND_LINE (bfd_find_nearest_line(abfd, text, syms, offset, &frame.file, &frame.function, &frame.line) && frame.file)
#endif

using namespace mlpack;

// Initialize Backtrace static inctances.
Backtrace::Frames Backtrace::frame;
std::vector<Backtrace::Frames> Backtrace::stack;

#ifdef HAS_BFD_DL
// Binary File Descriptor objects.
bfd* abfd = 0;		// Descriptor datastructure.
asymbol **syms = 0;	// Symbols datastructure.
asection *text = 0;	// Strings datastructure.
#endif

#ifdef HAS_BFD_DL
Backtrace::Backtrace(int maxDepth)
{
  frame.address = NULL;
  frame.function = "0";
  frame.file = "0";
  frame.line = 0;

  stack.clear();

  GetAddress(maxDepth);
}
#else
Backtrace::Backtrace()
{
  // Dummy constructor
}
#endif

#ifdef HAS_BFD_DL
void Backtrace::GetAddress(int maxDepth)
{
  void* trace[maxDepth];
  int stackDepth = backtrace(trace, maxDepth);

  // Skip first stack frame (points to Backtrace::Backtrace).
  for (int i = 1; i < stackDepth; i++)
  {
    Dl_info addressHandler;

    //No backtrace will be printed if no compile flags: -g -rdynamic
    if(TRACE_CONDITION_1)
    {
      return ;
    }

    frame.address = addressHandler.dli_saddr;

    DecodeAddress((long)frame.address);
  }
}

void Backtrace::DecodeAddress(long addr)
{
  // Check to see if there is anything to descript. If it doesn't, we'll
  // dump running program.
  if (!abfd)
  {
    char ename[1024];
    int l = readlink("/proc/self/exe",ename,sizeof(ename));
    if (l == -1)
    {
      perror("Failed to open executable!\n");
      return;
    }
    ename[l] = 0;

    bfd_init();

    abfd = bfd_openr(ename, 0);
    if (!abfd)
    {
      perror("bfd_openr failed: ");
      return;
    }

    bfd_check_format(abfd,bfd_object);

    unsigned storage_needed = bfd_get_symtab_upper_bound(abfd);
    syms = (asymbol **) malloc(storage_needed);

    text = bfd_get_section_by_name(abfd, ".text");
   }

  long offset = addr - text->vma;

  if (offset > 0)
  {
    if(FIND_LINE)
    {
      DemangleFunction();
      // Save retrieved informations.
      stack.push_back(frame);
    }
  }
}

void Backtrace::DemangleFunction()
{
  int status;
  char* tmp = abi::__cxa_demangle(frame.function, 0, 0, &status);

  // If demangling is successful, reallocate 'frame.function' pointer to
  // demangled name. Else if 'status != 0', leave 'frame.function as it is.
  if (status == 0)
  {
    frame.function = tmp;
  }
}
#else
void Backtrace::GetAddress(int /* maxDepth */) { }
void Backtrace::DecodeAddress(long /* address */) { }
void Backtrace::DemangleFunction() { }
#endif

std::string Backtrace::ToString()
{
  std::string stackStr;

#ifdef HAS_BFD_DL
  std::ostringstream lineOss;
  std::ostringstream it;

  if(stack.size() <= 0)
  {
    stackStr = "Cannot give backtrace because program was compiled";
    stackStr += " without: -g -rdynamic\nFor a backtrace,";
    stackStr += " recompile with: -g -rdynamic.\n";

    return stackStr;
  }

  for(unsigned int i = 0; i < stack.size(); i++)
  {
    frame = stack[i];

    lineOss << frame.line;
    it << i + 1;

      stackStr += "[bt]: (" + it.str() + ") "
	       + frame.file + ":"
	       + lineOss.str() + " "
	       + frame.function + ":\n";

    lineOss.str("");
    it.str("");
  }
#else
  stackStr = "[bt]: No backtrace for this OS. Work in progress.";
#endif

  return stackStr;
}
<|endoftext|>


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

#ifndef SD_LAYER_TAB_BAR_HXX
#define SD_LAYER_TAB_BAR_HXX

#ifndef _TABBAR_HXX
#include <svtools/tabbar.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

namespace sd {

/*************************************************************************
|*
|* TabBar fuer die Layerverwaltung
|*
\************************************************************************/

class DrawViewShell;

class LayerTabBar
    : public TabBar,
      public DropTargetHelper
{
public:
    LayerTabBar (
        DrawViewShell* pDrViewSh,
        ::Window* pParent);
    virtual ~LayerTabBar (void);

    /** Inform all listeners of this control that the current layer has been
        activated.  Call this method after switching the current layer and is
        not done elsewhere (like when using ctrl + page up/down keys).
    */
    void SendActivatePageEvent (void);

    /** Inform all listeners of this control that the current layer has been
        deactivated.  Call this method before switching the current layer
        and is not done elsewhere (like when using ctrl page up/down keys).
    */
    void SendDeactivatePageEvent (void);

protected:
    DrawViewShell* pDrViewSh;

    // TabBar
    virtual void        Select();
    virtual void        DoubleClick();
    virtual void        MouseButtonDown(const MouseEvent& rMEvt);

    virtual void        Command(const CommandEvent& rCEvt);

    virtual long        StartRenaming();
    virtual long        AllowRenaming();
    virtual void        EndRenaming();

    virtual void        ActivatePage();

    // DropTargetHelper
    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );
};

} // end of namespace sd

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

#ifndef SD_LAYER_TAB_BAR_HXX
#define SD_LAYER_TAB_BAR_HXX

#ifndef _TABBAR_HXX
#include <svtools/tabbar.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

namespace sd {

/*************************************************************************
|*
|* TabBar fuer die Layerverwaltung
|*
\************************************************************************/

class DrawViewShell;

class LayerTabBar
    : public TabBar,
      public DropTargetHelper
{
public:
    LayerTabBar (
        DrawViewShell* pDrViewSh,
        ::Window* pParent);
    LayerTabBar (
        DrawViewShell* pDrViewSh,
        ::Window* pParent,
        const ResId& rResId);
    virtual ~LayerTabBar (void);

    /** Inform all listeners of this control that the current layer has been
        activated.  Call this method after switching the current layer and is
        not done elsewhere (like when using ctrl + page up/down keys).
    */
    void SendActivatePageEvent (void);

    /** Inform all listeners of this control that the current layer has been
        deactivated.  Call this method before switching the current layer
        and is not done elsewhere (like when using ctrl page up/down keys).
    */
    void SendDeactivatePageEvent (void);

protected:
    DrawViewShell* pDrViewSh;

    // TabBar
    virtual void        Select();
    virtual void        DoubleClick();
    virtual void        MouseButtonDown(const MouseEvent& rMEvt);

    virtual void        Command(const CommandEvent& rCEvt);

    virtual long        StartRenaming();
    virtual long        AllowRenaming();
    virtual void        EndRenaming();

    virtual void        ActivatePage();

    // DropTargetHelper
    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );
};

} // end of namespace sd

#endif
<|endoftext|>