<commit_before>/*  -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
    Copyright (C) 2001 by Jorrit Tyberghein

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
#include "csutil/sysfunc.h"
#include "iutil/vfs.h"
#include "csutil/cscolor.h"
#include "cstool/csview.h"
#include "cstool/initapp.h"
#include "vostest.h"
#include "iutil/eventq.h"
#include "iutil/event.h"
#include "iutil/objreg.h"
#include "iutil/csinput.h"
#include "iutil/virtclk.h"
#include "iengine/sector.h"
#include "iengine/engine.h"
#include "iengine/camera.h"
#include "iengine/light.h"
#include "iengine/texture.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "iengine/material.h"
#include "imesh/thing/polygon.h"
#include "imesh/thing/thing.h"
#include "imesh/object.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/txtmgr.h"
#include "ivideo/texture.h"
#include "ivideo/material.h"
#include "ivideo/fontserv.h"
#include "ivideo/natwin.h"
#include "igraphic/imageio.h"
#include "imap/parser.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "csutil/cmdhelp.h"
#include "csutil/event.h"

#include "inetwork/vosa3dl.h"

#include <iostream>

CS_IMPLEMENT_APPLICATION

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

// The global pointer to vostest
Vostest *vostest;

Vostest::Vostest (iObjectRegistry* object_reg)
{
  Vostest::object_reg = object_reg;
}

Vostest::~Vostest ()
{
}

void Vostest::SetupFrame ()
{
  // First get elapsed time from the virtual clock.
  csTicks elapsed_time = vc->GetElapsedTicks ();
  // Now rotate the camera according to keyboard state
  float speed = (elapsed_time / 1000.0) * (0.06 * 20);

  iCamera* c = view->GetCamera();

  if (kbd->GetKeyState (CSKEY_SHIFT)) {
      if (kbd->GetKeyState (CSKEY_RIGHT))
          c->Move (CS_VEC_RIGHT * 4 * speed);
      if (kbd->GetKeyState (CSKEY_LEFT))
          c->Move (CS_VEC_LEFT * 4 * speed);
      if (kbd->GetKeyState (CSKEY_UP))
          c->Move (CS_VEC_UP * 4 * speed);
      if (kbd->GetKeyState (CSKEY_DOWN))
          c->Move (CS_VEC_DOWN * 4 * speed);
  } else {
      if (kbd->GetKeyState (CSKEY_RIGHT))
          rotY += speed;
      if (kbd->GetKeyState (CSKEY_LEFT))
          rotY -= speed;
      if (kbd->GetKeyState (CSKEY_PGUP))
          rotX += speed;
      if (kbd->GetKeyState (CSKEY_PGDN))
          rotX -= speed;
      if (kbd->GetKeyState (CSKEY_UP))
          c->Move (CS_VEC_FORWARD * 4 * speed);
      if (kbd->GetKeyState (CSKEY_DOWN))
          c->Move (CS_VEC_BACKWARD * 4 * speed);
  }

  csMatrix3 rot =  csXRotMatrix3(rotX) * csYRotMatrix3(rotY);
  csOrthoTransform ot(rot, c->GetTransform().GetOrigin());
  c->SetTransform(ot);

  // Tell 3D driver we're going to display 3D things.
  if (!g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS | CSDRAW_CLEARZBUFFER | CSDRAW_CLEARSCREEN))
    return;

  // Tell the camera to render into the frame buffer.
  view->Draw ();
}

void Vostest::FinishFrame ()
{
  g3d->FinishDraw ();
  g3d->Print (0);
}

bool Vostest::HandleEvent (iEvent& ev)
{
  if (ev.Type == csevBroadcast && ev.Command.Code == cscmdProcess)
  {
    std::cout << "HandleEvent SetupFrame\n";
    vostest->SetupFrame ();
    return true;
  }
  else if (ev.Type == csevBroadcast && ev.Command.Code == cscmdFinalProcess)
  {
    std::cout << "HandleEvent FinishFrame\n";
    vostest->FinishFrame ();
    return true;
  }
  else if ((ev.Type == csevKeyboard) &&
    (csKeyEventHelper::GetEventType (&ev) == csKeyEventTypeDown) &&
    (csKeyEventHelper::GetCookedCode (&ev) == CSKEY_ESC))
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q) q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }

  return false;
}

bool Vostest::VostestEventHandler (iEvent& ev)
{
  return vostest->HandleEvent (ev);
}

bool Vostest::Initialize ()
{
  if (!csInitializer::RequestPlugins (object_reg,
                                      CS_REQUEST_VFS,
                                      CS_REQUEST_OPENGL3D,
                                      CS_REQUEST_ENGINE,
                                      CS_REQUEST_FONTSERVER,
                                      CS_REQUEST_IMAGELOADER,
                                      CS_REQUEST_LEVELLOADER,
                                      CS_REQUEST_REPORTER,
                                      CS_REQUEST_REPORTERLISTENER,
                                      CS_REQUEST_PLUGIN("crystalspace.network.vos.a3dl", iVosA3DL),
                                      CS_REQUEST_END))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "Can't initialize plugins!");
    return false;
  }

  if (!csInitializer::SetupEventHandler (object_reg, VostestEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "Can't initialize event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    return false;
  }

  // The virtual clock.
  vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock);
  if (vc == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "Can't find the virtual clock!");
    return false;
  }

  // Find the pointer to engine plugin
  engine = CS_QUERY_REGISTRY (object_reg, iEngine);
  if (engine == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "No iEngine plugin!");
    return false;
  }

  loader = CS_QUERY_REGISTRY (object_reg, iLoader);
  if (loader == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iLoader plugin!");
    return false;
  }

  g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D);
  if (g3d == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iGraphics3D plugin!");
    return false;
  }

  kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver);
  if (kbd == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iKeyboardDriver plugin!");
    return false;
  }

  vosa3dl = CS_QUERY_REGISTRY (object_reg, iVosA3DL);
  if (vosa3dl == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iVosA3DL plugin!");
    return false;
  }

  // Open the main system. This will open all the previously loaded plug-ins.
  if (!csInitializer::OpenApplication (object_reg))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "Error opening system!");
    return false;
  }

  rotY = 0;
  rotX = 0;

  // First disable the lighting cache. Our app is simple enough
  // not to need this.
  engine->SetLightingCacheMode (0);

  if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif"))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "Error loading 'stone4' texture!");
    return false;
  }
  iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone");

  engine->Prepare ();

  csRef<iVosSector> vossector = vosa3dl->GetSector("vop://localhost/world");
  vossector->Load();
  room = vossector->GetSector();

  std::cout << "yearg 1\n";

  view = csPtr<iView> (new csView (engine, g3d));
  view->GetCamera ()->SetSector (room);
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
  iGraphics2D* g2d = g3d->GetDriver2D ();
  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());

  std::cout << "yearg 2\n";

  return true;
}

void Vostest::Start ()
{
  csDefaultRunLoop (object_reg);
}

/*---------------------------------------------------------------------*
 * Main function
 *---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
  iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);

  vostest = new Vostest (object_reg);
  if (vostest->Initialize ())
    vostest->Start ();
  delete vostest;

  csInitializer::DestroyApplication (object_reg);
  return 0;
}

<commit_msg>Figured out a workaround for a crashing bug<commit_after>/*  -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
    Copyright (C) 2001 by Jorrit Tyberghein

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"
//#include "csutil/sysfunc.h"
#include "iutil/vfs.h"
#include "csutil/cscolor.h"
#include "cstool/csview.h"
#include "cstool/initapp.h"
#include "vostest.h"
#include "iutil/eventq.h"
#include "iutil/event.h"
#include "iutil/objreg.h"
#include "iutil/csinput.h"
#include "iutil/virtclk.h"
#include "iutil/plugin.h"
#include "iengine/sector.h"
#include "iengine/engine.h"
#include "iengine/camera.h"
#include "iengine/light.h"
#include "iengine/texture.h"
#include "iengine/mesh.h"
#include "iengine/movable.h"
#include "iengine/material.h"
#include "imesh/thing/polygon.h"
#include "imesh/thing/thing.h"
#include "imesh/object.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/txtmgr.h"
#include "ivideo/texture.h"
#include "ivideo/material.h"
#include "ivideo/fontserv.h"
#include "ivideo/natwin.h"
#include "igraphic/imageio.h"
#include "imap/parser.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "ivaria/engseq.h"
#include "csutil/cmdhelp.h"
#include "csutil/event.h"

#include "inetwork/vosa3dl.h"

#include <iostream>

CS_IMPLEMENT_APPLICATION

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

// The global pointer to vostest
Vostest *vostest;

Vostest::Vostest (iObjectRegistry* object_reg)
{
  Vostest::object_reg = object_reg;
}

Vostest::~Vostest ()
{
}

void Vostest::SetupFrame ()
{
  // First get elapsed time from the virtual clock.
  csTicks elapsed_time = vc->GetElapsedTicks ();
  // Now rotate the camera according to keyboard state
  float speed = (elapsed_time / 1000.0) * (0.06 * 20);

  iCamera* c = view->GetCamera();

  if (kbd->GetKeyState (CSKEY_SHIFT)) {
      if (kbd->GetKeyState (CSKEY_RIGHT))
          c->Move (CS_VEC_RIGHT * 4 * speed);
      if (kbd->GetKeyState (CSKEY_LEFT))
          c->Move (CS_VEC_LEFT * 4 * speed);
      if (kbd->GetKeyState (CSKEY_UP))
          c->Move (CS_VEC_UP * 4 * speed);
      if (kbd->GetKeyState (CSKEY_DOWN))
          c->Move (CS_VEC_DOWN * 4 * speed);
  } else {
      if (kbd->GetKeyState (CSKEY_RIGHT))
          rotY += speed;
      if (kbd->GetKeyState (CSKEY_LEFT))
          rotY -= speed;
      if (kbd->GetKeyState (CSKEY_PGUP))
          rotX += speed;
      if (kbd->GetKeyState (CSKEY_PGDN))
          rotX -= speed;
      if (kbd->GetKeyState (CSKEY_UP))
          c->Move (CS_VEC_FORWARD * 4 * speed);
      if (kbd->GetKeyState (CSKEY_DOWN))
          c->Move (CS_VEC_BACKWARD * 4 * speed);
  }

  csMatrix3 rot =  csXRotMatrix3(rotX) * csYRotMatrix3(rotY);
  csOrthoTransform ot(rot, c->GetTransform().GetOrigin());
  c->SetTransform(ot);

  // Tell 3D driver we're going to display 3D things.
  if (!g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS | CSDRAW_CLEARZBUFFER | CSDRAW_CLEARSCREEN))
    return;

  // Tell the camera to render into the frame buffer.
  view->Draw ();
}

void Vostest::FinishFrame ()
{
  g3d->FinishDraw ();
  g3d->Print (0);
}

bool Vostest::HandleEvent (iEvent& ev)
{
  if (ev.Type == csevBroadcast && ev.Command.Code == cscmdProcess)
  {
    vostest->SetupFrame ();
    return true;
  }
  else if (ev.Type == csevBroadcast && ev.Command.Code == cscmdFinalProcess)
  {
    vostest->FinishFrame ();
    return true;
  }
  else if ((ev.Type == csevKeyboard) &&
    (csKeyEventHelper::GetEventType (&ev) == csKeyEventTypeDown) &&
    (csKeyEventHelper::GetCookedCode (&ev) == CSKEY_ESC))
  {
    csRef<iEventQueue> q (CS_QUERY_REGISTRY (object_reg, iEventQueue));
    if (q) q->GetEventOutlet()->Broadcast (cscmdQuit);
    return true;
  }

  return false;
}

bool Vostest::VostestEventHandler (iEvent& ev)
{
  return vostest->HandleEvent (ev);
}

bool Vostest::Initialize ()
{
  if (!csInitializer::RequestPlugins (object_reg,
                                      CS_REQUEST_VFS,
                                      CS_REQUEST_OPENGL3D,
                                      CS_REQUEST_ENGINE,
                                      CS_REQUEST_FONTSERVER,
                                      CS_REQUEST_IMAGELOADER,
                                      CS_REQUEST_LEVELLOADER,
                                      CS_REQUEST_REPORTER,
                                      CS_REQUEST_REPORTERLISTENER,
                                      CS_REQUEST_PLUGIN("crystalspace.network.vos.a3dl", iVosA3DL),
                                      CS_REQUEST_END))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "Can't initialize plugins!");
    return false;
  }

  if (!csInitializer::SetupEventHandler (object_reg, VostestEventHandler))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "Can't initialize event handler!");
    return false;
  }

  // Check for commandline help.
  if (csCommandLineHelper::CheckHelp (object_reg))
  {
    csCommandLineHelper::Help (object_reg);
    return false;
  }

  // The virtual clock.
  vc = CS_QUERY_REGISTRY (object_reg, iVirtualClock);
  if (vc == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "Can't find the virtual clock!");
    return false;
  }

  // Find the pointer to engine plugin
  engine = CS_QUERY_REGISTRY (object_reg, iEngine);
  if (engine == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
    "No iEngine plugin!");
    return false;
  }

#if 0
  csRef<iPluginManager> pm = CS_QUERY_REGISTRY (object_reg, iPluginManager);
  pm->LoadPlugin("crystalspace.utilities.sequence.engine", "iEngineSequenceManager", 3, true);
  pm->LoadPlugin("crystalspace.culling.frustvis", "iVisibilityCuller", 262144, true);
#endif

  loader = CS_QUERY_REGISTRY (object_reg, iLoader);
  if (loader == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iLoader plugin!");
    return false;
  }

  g3d = CS_QUERY_REGISTRY (object_reg, iGraphics3D);
  if (g3d == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iGraphics3D plugin!");
    return false;
  }

  kbd = CS_QUERY_REGISTRY (object_reg, iKeyboardDriver);
  if (kbd == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iKeyboardDriver plugin!");
    return false;
  }

  vosa3dl = CS_QUERY_REGISTRY (object_reg, iVosA3DL);
  if (vosa3dl == 0)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "No iVosA3DL plugin!");
    return false;
  }

  // Open the main system. This will open all the previously loaded plug-ins.
  if (!csInitializer::OpenApplication (object_reg))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "Error opening system!");
    return false;
  }

  rotY = 0;
  rotX = 0;

  // First disable the lighting cache. Our app is simple enough
  // not to need this.
  engine->SetLightingCacheMode (0);

  if (!loader->LoadTexture ("stone", "/lib/std/stone4.gif"))
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
        "crystalspace.application.vostest",
        "Error loading 'stone4' texture!");
    return false;
  }
  iMaterialWrapper* tm = engine->GetMaterialList ()->FindByName ("stone");

  engine->Prepare ();

  view = csPtr<iView> (new csView (engine, g3d));
  view->GetCamera ()->SetSector (engine->CreateSector("_tmp"));
  view->GetCamera ()->GetTransform ().SetOrigin (csVector3 (0, 5, -3));
  iGraphics2D* g2d = g3d->GetDriver2D ();
  view->SetRectangle (0, 0, g2d->GetWidth (), g2d->GetHeight ());

  if (!g3d->BeginDraw (engine->GetBeginDrawFlags () | CSDRAW_3DGRAPHICS | CSDRAW_CLEARZBUFFER | CSDRAW_CLEARSCREEN));
  view->Draw ();

  csRef<iVosSector> vossector = vosa3dl->GetSector("vop://localhost/world");
  vossector->Load();
  view->GetCamera()->SetSector(vossector->GetSector());

  return true;
}

void Vostest::Start ()
{
  csDefaultRunLoop (object_reg);
}

/*---------------------------------------------------------------------*
 * Main function
 *---------------------------------------------------------------------*/
int main (int argc, char* argv[])
{
  iObjectRegistry* object_reg = csInitializer::CreateEnvironment (argc, argv);

  vostest = new Vostest (object_reg);
  if (vostest->Initialize ())
    vostest->Start ();
  delete vostest;

  csInitializer::DestroyApplication (object_reg);
  return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "paddle/fluid/framework/ir/fc_lstm_fuse_pass.h"
#include <string>
#include <unordered_set>

#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_version_registry.h"

namespace paddle {
namespace framework {
namespace ir {

class Node;

int BuildFusion(Graph* graph, const std::string& name_scope, Scope* scope,
                bool with_fc_bias) {
  GraphPatternDetector gpd;
  auto* pattern = gpd.mutable_pattern();

  // Build pattern
  PDNode* x = pattern->NewNode(patterns::PDNodeName(name_scope, "x"))
                  ->assert_is_op_input("mul")
                  ->assert_var_not_persistable();
  patterns::FC fc_pattern(pattern, name_scope);

  // fc_out is a tmp var, will be removed after fuse, so marked as intermediate.
  auto* fc_out =
      fc_pattern(x, with_fc_bias, /* with_relu */ false)->AsIntermediate();
  patterns::LSTM lstm_pattern(pattern, name_scope);
  lstm_pattern(fc_out);

  // Create New OpDesc
  auto lstm_creator = [&](Node* lstm, Node* input, Node* weight_x,
                          Node* weight_h, Node* bias, Node* hidden, Node* cell,
                          Node* xx, Node* fc_bias) {
    OpDesc op_desc;
    op_desc.SetType("fusion_lstm");
#define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()});
    SET_IN(X, input);
    SET_IN(WeightX, weight_x);
    SET_IN(WeightH, weight_h);
    SET_IN(Bias, bias);
#undef SET_IN
    if (with_fc_bias) {
      // Add FC-bias with LSTM-bias and create a new weight
      PADDLE_ENFORCE_NOT_NULL(
          scope, platform::errors::InvalidArgument("Scope cannot be nullptr."));
      const std::string& new_bias_var = patterns::UniqueKey("NewBias");
      auto* bias_var = scope->Var(new_bias_var);
      PADDLE_ENFORCE_NOT_NULL(bias_var, platform::errors::InvalidArgument(
                                            "Bias var ptr cannot be nullptr."));
      auto* bias_tensor = bias_var->GetMutable<framework::LoDTensor>();
      auto* lstm_bias_var = scope->FindVar(bias->Name());
      PADDLE_ENFORCE_NOT_NULL(lstm_bias_var,
                              platform::errors::InvalidArgument(
                                  "Lstm bias var ptr cannot be nullptr."));
      const auto& lstm_bias_tensor = lstm_bias_var->Get<framework::LoDTensor>();
      bias_tensor->Resize(lstm_bias_tensor.dims());

      auto* fc_bias_var = scope->FindVar(fc_bias->Name());
      const auto& fc_bias_tensor = fc_bias_var->Get<framework::LoDTensor>();

      auto* data = bias_tensor->mutable_data<float>(platform::CPUPlace());

      for (int i = 0; i < bias_tensor->numel(); i++) {
        data[i] =
            fc_bias_tensor.data<float>()[i] + lstm_bias_tensor.data<float>()[i];
      }
      op_desc.SetInput("Bias", {new_bias_var});
    }

    op_desc.SetInput("H0", {});
    op_desc.SetInput("C0", {});
    op_desc.SetOutput("Hidden", {hidden->Name()});
    op_desc.SetOutput("Cell", {cell->Name()});
    op_desc.SetOutput("XX", {xx->Name()});
    op_desc.SetAttr("is_reverse", lstm->Op()->GetAttr("is_reverse"));
    op_desc.SetAttr("use_peepholes", lstm->Op()->GetAttr("use_peepholes"));
    // TODO(TJ): get from attr
    op_desc.SetAttr("use_seq", true);

// Create temp variables.
#define OP_SET_OUT(x)                            \
  const std::string x = patterns::UniqueKey(#x); \
  op_desc.SetOutput(#x, {x});

    OP_SET_OUT(BatchedGate);
    OP_SET_OUT(BatchedCellPreAct);
    OP_SET_OUT(BatchedInput);
    OP_SET_OUT(CheckedCell);
    OP_SET_OUT(BatchedCell);
    OP_SET_OUT(BatchedHidden);
    OP_SET_OUT(ReorderedH0);
    OP_SET_OUT(ReorderedC0);
#undef OP_SET_OUT

    auto* op = graph->CreateOpNode(&op_desc);

    IR_NODE_LINK_TO(input, op);
    IR_NODE_LINK_TO(weight_x, op);
    IR_NODE_LINK_TO(weight_h, op);
    IR_NODE_LINK_TO(bias, op);
    IR_NODE_LINK_TO(op, hidden);

#define IR_NODE(x)                                 \
  VarDesc key_##x(x);                              \
  key_##x.SetPersistable(false);                   \
  auto* node_##x = graph->CreateVarNode(&key_##x); \
  IR_NODE_LINK_TO(op, node_##x);

    IR_NODE(BatchedGate);
    IR_NODE(BatchedCellPreAct);
    IR_NODE(BatchedInput);
    IR_NODE(CheckedCell);
    IR_NODE(BatchedCell);
    IR_NODE(BatchedHidden);
    IR_NODE(ReorderedH0);
    IR_NODE(ReorderedC0);
#undef IR_NODE

    return op;
  };

  int fusion_count{0};

  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    GET_IR_NODE_FROM_SUBGRAPH(lstm, lstm, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Weight, Weight, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Bias, Bias, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(BatchCellPreAct, BatchCellPreAct, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(BatchGate, BatchGate, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Cell, Cell, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
    if (with_fc_bias) {
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, elementwise_add_out, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
                   fc_bias);
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
          {mul, lstm, elementwise_add, mul_out, BatchGate, BatchCellPreAct});
      GraphSafeRemoveNodes(graph, marked_nodes);
    } else {
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, mul_out, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
                   nullptr);
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
          {mul, lstm, BatchGate, BatchCellPreAct});
      GraphSafeRemoveNodes(graph, marked_nodes);
    }

    ++fusion_count;
  };

  gpd(graph, handler);

  return fusion_count;
}

void MulLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);

  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), false /*with_fc_bias*/);

  AddStatis(fusion_count);
}

void FCLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);

  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), true /*with_fc_bias*/);

  AddStatis(fusion_count);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(mul_lstm_fuse_pass, paddle::framework::ir::MulLstmFusePass);
REGISTER_PASS(fc_lstm_fuse_pass, paddle::framework::ir::FCLstmFusePass);

REGISTER_PASS_CAPABILITY(fc_lstm_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
            .EQ("elementwise_add", 0)
            .EQ("lstm", 0)
            .EQ("fusion_lstm", 0));
REGISTER_PASS_CAPABILITY(mul_lstm_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
            .EQ("lstm", 0)
            .EQ("fusion_lstm", 0));
<commit_msg>a fix for the fc_lstm_fuse_pass (#28709)<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "paddle/fluid/framework/ir/fc_lstm_fuse_pass.h"
#include <string>
#include <unordered_set>

#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_version_registry.h"

namespace paddle {
namespace framework {
namespace ir {

class Node;

int BuildFusion(Graph* graph, const std::string& name_scope, Scope* scope,
                bool with_fc_bias) {
  GraphPatternDetector gpd;
  auto* pattern = gpd.mutable_pattern();

  // Build pattern
  PDNode* x = pattern->NewNode(patterns::PDNodeName(name_scope, "x"))
                  ->assert_is_op_input("mul")
                  ->assert_var_not_persistable();
  patterns::FC fc_pattern(pattern, name_scope);

  auto* fc_out = fc_pattern(x, with_fc_bias, /* with_relu */ false);
  patterns::LSTM lstm_pattern(pattern, name_scope);
  lstm_pattern(fc_out);

  // Create New OpDesc
  auto lstm_creator = [&](Node* lstm, Node* input, Node* weight_x,
                          Node* weight_h, Node* bias, Node* hidden, Node* cell,
                          Node* xx, Node* fc_bias) {
    OpDesc op_desc;
    op_desc.SetType("fusion_lstm");
#define SET_IN(Key, node__) op_desc.SetInput(#Key, {node__->Name()});
    SET_IN(X, input);
    SET_IN(WeightX, weight_x);
    SET_IN(WeightH, weight_h);
    SET_IN(Bias, bias);
#undef SET_IN
    if (with_fc_bias) {
      // Add FC-bias with LSTM-bias and create a new weight
      PADDLE_ENFORCE_NOT_NULL(
          scope, platform::errors::InvalidArgument("Scope cannot be nullptr."));
      auto* lstm_bias_var = scope->FindVar(bias->Name());
      auto* fc_bias_var = scope->FindVar(fc_bias->Name());
      PADDLE_ENFORCE_NOT_NULL(lstm_bias_var,
                              platform::errors::InvalidArgument(
                                  "Lstm bias var ptr cannot be nullptr."));
      PADDLE_ENFORCE_NOT_NULL(fc_bias_var,
                              platform::errors::InvalidArgument(
                                  "FC bias var ptr cannot be nullptr."));
      auto* lstm_bias_tensor =
          lstm_bias_var->GetMutable<framework::LoDTensor>();
      const auto& fc_bias_tensor = fc_bias_var->Get<framework::LoDTensor>();

      auto lstm_bias_data =
          lstm_bias_tensor->mutable_data<float>(platform::CPUPlace());
      auto* fc_bias_data = fc_bias_tensor.data<float>();

      for (int i = 0; i < lstm_bias_tensor->numel(); i++) {
        lstm_bias_data[i] += fc_bias_data[i];
      }
    }

    op_desc.SetInput("H0", {});
    op_desc.SetInput("C0", {});
    op_desc.SetOutput("Hidden", {hidden->Name()});
    op_desc.SetOutput("Cell", {cell->Name()});
    op_desc.SetOutput("XX", {xx->Name()});
    op_desc.SetAttr("is_reverse", lstm->Op()->GetAttr("is_reverse"));
    op_desc.SetAttr("use_peepholes", lstm->Op()->GetAttr("use_peepholes"));
    // TODO(TJ): get from attr
    op_desc.SetAttr("use_seq", true);

// Create temp variables.
#define OP_SET_OUT(x)                            \
  const std::string x = patterns::UniqueKey(#x); \
  op_desc.SetOutput(#x, {x});

    OP_SET_OUT(BatchedGate);
    OP_SET_OUT(BatchedCellPreAct);
    OP_SET_OUT(BatchedInput);
    OP_SET_OUT(CheckedCell);
    OP_SET_OUT(BatchedCell);
    OP_SET_OUT(BatchedHidden);
    OP_SET_OUT(ReorderedH0);
    OP_SET_OUT(ReorderedC0);
#undef OP_SET_OUT

    auto* op = graph->CreateOpNode(&op_desc);

    IR_NODE_LINK_TO(input, op);
    IR_NODE_LINK_TO(weight_x, op);
    IR_NODE_LINK_TO(weight_h, op);
    IR_NODE_LINK_TO(bias, op);
    IR_NODE_LINK_TO(op, hidden);
    IR_NODE_LINK_TO(op, cell);
    IR_NODE_LINK_TO(op, xx);

#define IR_NODE(x)                                 \
  VarDesc key_##x(x);                              \
  key_##x.SetPersistable(false);                   \
  auto* node_##x = graph->CreateVarNode(&key_##x); \
  IR_NODE_LINK_TO(op, node_##x);

    IR_NODE(BatchedGate);
    IR_NODE(BatchedCellPreAct);
    IR_NODE(BatchedInput);
    IR_NODE(CheckedCell);
    IR_NODE(BatchedCell);
    IR_NODE(BatchedHidden);
    IR_NODE(ReorderedH0);
    IR_NODE(ReorderedC0);
#undef IR_NODE

    return op;
  };

  int fusion_count{0};

  auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
                     Graph* g) {
    GET_IR_NODE_FROM_SUBGRAPH(lstm, lstm, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Weight, Weight, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Bias, Bias, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Hidden, Hidden, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(BatchCellPreAct, BatchCellPreAct, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(BatchGate, BatchGate, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(Cell, Cell, lstm_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(w, w, fc_pattern);
    GET_IR_NODE_FROM_SUBGRAPH(mul, mul, fc_pattern);
    if (with_fc_bias) {
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, elementwise_add_out, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(fc_bias, bias, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(mul_out, mul_out, fc_pattern);
      GET_IR_NODE_FROM_SUBGRAPH(elementwise_add, elementwise_add, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
                   fc_bias);
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
          {mul, lstm, elementwise_add, mul_out, BatchGate, BatchCellPreAct});
      GraphSafeRemoveNodes(graph, marked_nodes);
    } else {
      GET_IR_NODE_FROM_SUBGRAPH(fc_out, mul_out, fc_pattern);
      lstm_creator(lstm, subgraph.at(x), w, Weight, Bias, Hidden, Cell, fc_out,
                   nullptr);
      // Remove unneeded nodes.
      std::unordered_set<const Node*> marked_nodes(
          {mul, lstm, BatchGate, BatchCellPreAct});
      GraphSafeRemoveNodes(graph, marked_nodes);
    }

    ++fusion_count;
  };

  gpd(graph, handler);

  return fusion_count;
}

void MulLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);

  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), false /*with_fc_bias*/);

  AddStatis(fusion_count);
}

void FCLstmFusePass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init(name_scope_, graph);

  int fusion_count =
      BuildFusion(graph, name_scope_, param_scope(), true /*with_fc_bias*/);

  AddStatis(fusion_count);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(mul_lstm_fuse_pass, paddle::framework::ir::MulLstmFusePass);
REGISTER_PASS(fc_lstm_fuse_pass, paddle::framework::ir::FCLstmFusePass);

REGISTER_PASS_CAPABILITY(fc_lstm_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
            .EQ("elementwise_add", 0)
            .EQ("lstm", 0)
            .EQ("fusion_lstm", 0));
REGISTER_PASS_CAPABILITY(mul_lstm_fuse_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination()
            .EQ("mul", 0)
            .EQ("lstm", 0)
            .EQ("fusion_lstm", 0));
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief AQL query/cursor request handler
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2010-2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "RestAqlHandler.h"

#include "Basics/ConditionLocker.h"
#include "Rest/HttpRequest.h"
#include "Rest/HttpResponse.h"

#include "HttpServer/HttpServer.h"
#include "HttpServer/HttpHandlerFactory.h"
#include "GeneralServer/GeneralServerJob.h"
#include "GeneralServer/GeneralServer.h"

using namespace std;
using namespace triagens::arango;
using namespace triagens::rest;
using namespace triagens::aql;

// -----------------------------------------------------------------------------
// --SECTION--                                                  public constants
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief name of the queue
////////////////////////////////////////////////////////////////////////////////

const string RestAqlHandler::QUEUE_NAME = "STANDARD";

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

RestAqlHandler::RestAqlHandler (triagens::rest::HttpRequest* request,
                   std::pair<ApplicationV8*, QueryRegistry*>* pair)
  : RestBaseHandler(request),
    _applicationV8(pair->first),
    _context(static_cast<VocbaseContext*>(request->getRequestContext())),
    _vocbase(_context->getVocbase()),
    _queryRegistry(pair->second) {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   Handler methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool RestAqlHandler::isDirect () {
  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

string const& RestAqlHandler::queue () const {
  return QUEUE_NAME;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void RestAqlHandler::createQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"a\":12}");

}

void RestAqlHandler::deleteQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"b\":12}");
}

void RestAqlHandler::useQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"c\":12}");
}

void RestAqlHandler::getInfoQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"d\":12}");
}

triagens::rest::HttpHandler::status_t RestAqlHandler::execute () {
  auto context = _applicationV8->enterContext("STANDARD", _vocbase, nullptr,
                                              false, false);
  if (nullptr == context) {
    generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL,
                  "cannot enter V8 context");
  }
  else {
    // extract the sub-request type
    HttpRequest::HttpRequestType type = _request->requestType();

    // execute one of the CRUD methods
    switch (type) {
      case HttpRequest::HTTP_REQUEST_POST: {
        createQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_DELETE: {
        deleteQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_PUT: {
        useQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_GET: {
        getInfoQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_HEAD: {
        _response = createResponse(triagens::rest::HttpResponse::METHOD_NOT_ALLOWED);
        break;
      }
      case HttpRequest::HTTP_REQUEST_PATCH:
      case HttpRequest::HTTP_REQUEST_OPTIONS:
      case HttpRequest::HTTP_REQUEST_ILLEGAL: {
        generateError(HttpResponse::METHOD_NOT_ALLOWED,
                      TRI_ERROR_NOT_IMPLEMENTED,
                      "illegal method for /_api/aql");
        break;
      }
    }

  }

  _applicationV8->exitContext(context);

  return status_t(HANDLER_DONE);
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Some more code for HTTP API for AQL.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief AQL query/cursor request handler
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2010-2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "RestAqlHandler.h"

#include "Basics/ConditionLocker.h"
#include "Rest/HttpRequest.h"
#include "Rest/HttpResponse.h"

#include "HttpServer/HttpServer.h"
#include "HttpServer/HttpHandlerFactory.h"
#include "GeneralServer/GeneralServerJob.h"
#include "GeneralServer/GeneralServer.h"

using namespace std;
using namespace triagens::arango;
using namespace triagens::rest;
using namespace triagens::aql;

using Json = triagens::basics::Json;

// -----------------------------------------------------------------------------
// --SECTION--                                                  public constants
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief name of the queue
////////////////////////////////////////////////////////////////////////////////

const string RestAqlHandler::QUEUE_NAME = "STANDARD";

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

RestAqlHandler::RestAqlHandler (triagens::rest::HttpRequest* request,
                   std::pair<ApplicationV8*, QueryRegistry*>* pair)
  : RestBaseHandler(request),
    _applicationV8(pair->first),
    _context(static_cast<VocbaseContext*>(request->getRequestContext())),
    _vocbase(_context->getVocbase()),
    _queryRegistry(pair->second) {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   Handler methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool RestAqlHandler::isDirect () {
  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

string const& RestAqlHandler::queue () const {
  return QUEUE_NAME;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void RestAqlHandler::createQuery () {
#if 0
  Json queryJson(parseJsonBody());
  if (queryJson.isEmpty()) {
    return;
  }
#endif

  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"a\":12}");

}

void RestAqlHandler::deleteQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"b\":12}");
}

void RestAqlHandler::useQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"c\":12}");
}

void RestAqlHandler::getInfoQuery () {
  _response = createResponse(triagens::rest::HttpResponse::OK);
  _response->setContentType("application/json; charset=utf-8");
  _response->body().appendText("{\"d\":12}");
}

triagens::rest::HttpHandler::status_t RestAqlHandler::execute () {
  auto context = _applicationV8->enterContext("STANDARD", _vocbase, nullptr,
                                              false, false);
  if (nullptr == context) {
    generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL,
                  "cannot enter V8 context");
  }
  else {
    // extract the sub-request type
    HttpRequest::HttpRequestType type = _request->requestType();

    // execute one of the CRUD methods
    switch (type) {
      case HttpRequest::HTTP_REQUEST_POST: {
        createQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_DELETE: {
        deleteQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_PUT: {
        useQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_GET: {
        getInfoQuery();
        break;
      }
      case HttpRequest::HTTP_REQUEST_HEAD: {
        _response = createResponse(triagens::rest::HttpResponse::METHOD_NOT_ALLOWED);
        break;
      }
      case HttpRequest::HTTP_REQUEST_PATCH:
      case HttpRequest::HTTP_REQUEST_OPTIONS:
      case HttpRequest::HTTP_REQUEST_ILLEGAL: {
        generateError(HttpResponse::METHOD_NOT_ALLOWED,
                      TRI_ERROR_NOT_IMPLEMENTED,
                      "illegal method for /_api/aql");
        break;
      }
    }

  }

  _applicationV8->exitContext(context);

  return status_t(HANDLER_DONE);
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Common.h"

#include "Basics/directories.h"
#include "Basics/tri-strings.h"

#include "Actions/ActionFeature.h"
#include "Agency/AgencyFeature.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "ApplicationFeatures/GreetingsFeature.h"
#include "ApplicationFeatures/JemallocFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/NonceFeature.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "ApplicationFeatures/RocksDBOptionFeature.h"
#include "Pregel/PregelFeature.h"
#include "ApplicationFeatures/PrivilegeFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/SupervisorFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Cache/CacheManagerFeature.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LoggerBufferFeature.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/BootstrapFeature.h"
#include "RestServer/CheckVersionFeature.h"
#include "RestServer/ConsoleFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/EndpointFeature.h"
#include "RestServer/FeatureCacheFeature.h"
#include "RestServer/FileDescriptorsFeature.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/InitDatabaseFeature.h"
#include "RestServer/LockfileFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ScriptFeature.h"
#include "RestServer/ServerFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "RestServer/TransactionManagerFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "RestServer/UnitTestsFeature.h"
#include "RestServer/UpgradeFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/WorkMonitorFeature.h"
#include "Scheduler/SchedulerFeature.h"
#include "Ssl/SslFeature.h"
#include "Ssl/SslServerFeature.h"
#include "Statistics/StatisticsFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"

#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"

#ifdef _WIN32
#include "ApplicationFeatures/WindowsServiceFeature.h"
#endif

#ifdef USE_ENTERPRISE
#include "Enterprise/RestServer/arangodEE.h"
#endif

// storage engine
#include "MMFiles/MMFilesEngine.h"
#include "RocksDBEngine/RocksDBEngine.h"

using namespace arangodb;

static int runServer(int argc, char** argv, ArangoGlobalContext &context) {
  try {
    context.installSegv();
    context.runStartupChecks();

    std::string name = context.binaryName();

    auto options = std::make_shared<options::ProgramOptions>(
        argv[0], "Usage: " + name + " [<options>]", "For more information use:",
        SBIN_DIRECTORY);

    application_features::ApplicationServer server(options, SBIN_DIRECTORY);

    std::vector<std::string> nonServerFeatures = {
        "Action",        "Affinity",
        "Agency",        "Authentication",
        "Cluster",       "Daemon",
        "FoxxQueues",    "GeneralServer",
        "Greetings",     "LoggerBufferFeature",
        "Server",        "SslServer",
        "Statistics",    "Supervisor"};

    int ret = EXIT_FAILURE;

    server.addFeature(new ActionFeature(&server));
    server.addFeature(new AgencyFeature(&server));
    server.addFeature(new aql::AqlFunctionFeature(&server));
    server.addFeature(new aql::OptimizerRulesFeature(&server));
    server.addFeature(new AuthenticationFeature(&server));
    server.addFeature(new AqlFeature(&server));
    server.addFeature(new BootstrapFeature(&server));
    server.addFeature(new CacheManagerFeature(&server));
    server.addFeature(
        new CheckVersionFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new ClusterFeature(&server));
    server.addFeature(new ConfigFeature(&server, name));
    server.addFeature(new ConsoleFeature(&server));
    server.addFeature(new DatabaseFeature(&server));
    server.addFeature(new DatabasePathFeature(&server));
    server.addFeature(new EndpointFeature(&server));
    server.addFeature(new EngineSelectorFeature(&server));
    server.addFeature(new FeatureCacheFeature(&server));
    server.addFeature(new FileDescriptorsFeature(&server));
    server.addFeature(new FoxxQueuesFeature(&server));
    server.addFeature(new FrontendFeature(&server));
    server.addFeature(new GeneralServerFeature(&server));
    server.addFeature(new GreetingsFeature(&server));
    server.addFeature(new InitDatabaseFeature(&server, nonServerFeatures));
    server.addFeature(new JemallocFeature(&server));
    server.addFeature(new LanguageFeature(&server));
    server.addFeature(new LockfileFeature(&server));
    server.addFeature(new LoggerBufferFeature(&server));
    server.addFeature(new LoggerFeature(&server, true));
    server.addFeature(new NonceFeature(&server));
    server.addFeature(new PageSizeFeature(&server));
    server.addFeature(new pregel::PregelFeature(&server));
    server.addFeature(new PrivilegeFeature(&server));
    server.addFeature(new RandomFeature(&server));
    server.addFeature(new QueryRegistryFeature(&server));
    server.addFeature(new SchedulerFeature(&server));
    server.addFeature(new ScriptFeature(&server, &ret));
    server.addFeature(new ServerFeature(&server, &ret));
    server.addFeature(new ServerIdFeature(&server));
    server.addFeature(new ShutdownFeature(&server, {"UnitTests", "Script"}));
    server.addFeature(new SslFeature(&server));
    server.addFeature(new StatisticsFeature(&server));
    server.addFeature(new TempFeature(&server, name));
    server.addFeature(new TransactionManagerFeature(&server));
    server.addFeature(new TraverserEngineRegistryFeature(&server));
    server.addFeature(new UnitTestsFeature(&server, &ret));
    server.addFeature(new UpgradeFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new V8DealerFeature(&server));
    server.addFeature(new V8PlatformFeature(&server));
    server.addFeature(new VersionFeature(&server));
    server.addFeature(new ViewTypesFeature(&server));
    server.addFeature(new WorkMonitorFeature(&server));
    server.addFeature(new RocksDBOptionFeature(&server));

#ifdef ARANGODB_HAVE_FORK
    server.addFeature(new DaemonFeature(&server));
    server.addFeature(new SupervisorFeature(&server));
#endif

#ifdef _WIN32
    server.addFeature(new WindowsServiceFeature(&server));
#endif

#ifdef USE_ENTERPRISE
    setupServerEE(&server);
#else
    server.addFeature(new SslServerFeature(&server));
#endif

    // storage engines
    server.addFeature(new MMFilesEngine(&server));
    server.addFeature(new RocksDBEngine(&server));

    try {
      server.run(argc, argv);
      if (server.helpShown()) {
        // --help was displayed
        ret = EXIT_SUCCESS;
      }
    } catch (std::exception const& ex) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception: "
          << ex.what();
      ret = EXIT_FAILURE;
    } catch (...) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception of "
             "unknown type";
      ret = EXIT_FAILURE;
    }
    Logger::flush();
    return context.exit(ret);
  } catch (std::exception const& ex) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an exception: "
        << ex.what();
  } catch (...) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an xception of "
           "unknown type";
  }
  exit(EXIT_FAILURE);
}

#if _WIN32
static int ARGC;
static char** ARGV;

static void WINAPI ServiceMain(DWORD dwArgc, LPSTR* lpszArgv) {
  if (!TRI_InitWindowsEventLog()) {
    return;
  }
  // register the service ctrl handler,  lpszArgv[0] contains service name
  ServiceStatus =
      RegisterServiceCtrlHandlerA(lpszArgv[0], (LPHANDLER_FUNCTION)ServiceCtrl);

  // set start pending
  SetServiceStatus(SERVICE_START_PENDING, 0, 1, 10000);

  ArangoGlobalContext context(ARGC, ARGV, SBIN_DIRECTORY);
  runServer(ARGC, ARGV, context);

  // service has stopped
  SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0);
  TRI_CloseWindowsEventlog();
}

#endif

int main(int argc, char* argv[]) {
#if _WIN32
  if (argc > 1 && TRI_EqualString("--start-service", argv[1])) {
    ARGC = argc;
    ARGV = argv;

    SERVICE_TABLE_ENTRY ste[] = {
      {TEXT(""), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {nullptr, nullptr}};

    if (!StartServiceCtrlDispatcher(ste)) {
      std::cerr << "FATAL: StartServiceCtrlDispatcher has failed with "
                << GetLastError() << std::endl;
      exit(EXIT_FAILURE);
    }
    return 0;
  }
#endif
  ArangoGlobalContext context(argc, argv, SBIN_DIRECTORY);
  return runServer(argc, argv, context);
}
<commit_msg>windows again<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Common.h"

#include "Basics/directories.h"
#include "Basics/tri-strings.h"

#include "Actions/ActionFeature.h"
#include "Agency/AgencyFeature.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "ApplicationFeatures/GreetingsFeature.h"
#include "ApplicationFeatures/JemallocFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/NonceFeature.h"
#include "ApplicationFeatures/PageSizeFeature.h"
#include "ApplicationFeatures/RocksDBOptionFeature.h"
#include "Pregel/PregelFeature.h"
#include "ApplicationFeatures/PrivilegeFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/SupervisorFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Aql/AqlFunctionFeature.h"
#include "Aql/OptimizerRulesFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Cache/CacheManagerFeature.h"
#include "Cluster/ClusterFeature.h"
#include "GeneralServer/AuthenticationFeature.h"
#include "GeneralServer/GeneralServerFeature.h"
#include "Logger/LoggerBufferFeature.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "RestServer/AqlFeature.h"
#include "RestServer/BootstrapFeature.h"
#include "RestServer/CheckVersionFeature.h"
#include "RestServer/ConsoleFeature.h"
#include "RestServer/DatabaseFeature.h"
#include "RestServer/DatabasePathFeature.h"
#include "RestServer/EndpointFeature.h"
#include "RestServer/FeatureCacheFeature.h"
#include "RestServer/FileDescriptorsFeature.h"
#include "RestServer/FrontendFeature.h"
#include "RestServer/InitDatabaseFeature.h"
#include "RestServer/LockfileFeature.h"
#include "RestServer/QueryRegistryFeature.h"
#include "RestServer/ScriptFeature.h"
#include "RestServer/ServerFeature.h"
#include "RestServer/ServerIdFeature.h"
#include "RestServer/TransactionManagerFeature.h"
#include "RestServer/TraverserEngineRegistryFeature.h"
#include "RestServer/UnitTestsFeature.h"
#include "RestServer/UpgradeFeature.h"
#include "RestServer/ViewTypesFeature.h"
#include "RestServer/WorkMonitorFeature.h"
#include "Scheduler/SchedulerFeature.h"
#include "Ssl/SslFeature.h"
#include "Ssl/SslServerFeature.h"
#include "Statistics/StatisticsFeature.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include "V8Server/FoxxQueuesFeature.h"
#include "V8Server/V8DealerFeature.h"

#ifdef _WIN32
#include "ApplicationFeatures/WindowsServiceFeature.h"
#endif

#ifdef USE_ENTERPRISE
#include "Enterprise/RestServer/arangodEE.h"
#endif

// storage engines
#include "MMFiles/MMFilesEngine.h"
#include "RocksDBEngine/RocksDBEngine.h"

#ifdef _WIN32
#include <iostream>
#endif

using namespace arangodb;

static int runServer(int argc, char** argv, ArangoGlobalContext &context) {
  try {
    context.installSegv();
    context.runStartupChecks();

    std::string name = context.binaryName();

    auto options = std::make_shared<options::ProgramOptions>(
        argv[0], "Usage: " + name + " [<options>]", "For more information use:",
        SBIN_DIRECTORY);

    application_features::ApplicationServer server(options, SBIN_DIRECTORY);

    std::vector<std::string> nonServerFeatures = {
        "Action",        "Affinity",
        "Agency",        "Authentication",
        "Cluster",       "Daemon",
        "FoxxQueues",    "GeneralServer",
        "Greetings",     "LoggerBufferFeature",
        "Server",        "SslServer",
        "Statistics",    "Supervisor"};

    int ret = EXIT_FAILURE;

    server.addFeature(new ActionFeature(&server));
    server.addFeature(new AgencyFeature(&server));
    server.addFeature(new aql::AqlFunctionFeature(&server));
    server.addFeature(new aql::OptimizerRulesFeature(&server));
    server.addFeature(new AuthenticationFeature(&server));
    server.addFeature(new AqlFeature(&server));
    server.addFeature(new BootstrapFeature(&server));
    server.addFeature(new CacheManagerFeature(&server));
    server.addFeature(
        new CheckVersionFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new ClusterFeature(&server));
    server.addFeature(new ConfigFeature(&server, name));
    server.addFeature(new ConsoleFeature(&server));
    server.addFeature(new DatabaseFeature(&server));
    server.addFeature(new DatabasePathFeature(&server));
    server.addFeature(new EndpointFeature(&server));
    server.addFeature(new EngineSelectorFeature(&server));
    server.addFeature(new FeatureCacheFeature(&server));
    server.addFeature(new FileDescriptorsFeature(&server));
    server.addFeature(new FoxxQueuesFeature(&server));
    server.addFeature(new FrontendFeature(&server));
    server.addFeature(new GeneralServerFeature(&server));
    server.addFeature(new GreetingsFeature(&server));
    server.addFeature(new InitDatabaseFeature(&server, nonServerFeatures));
    server.addFeature(new JemallocFeature(&server));
    server.addFeature(new LanguageFeature(&server));
    server.addFeature(new LockfileFeature(&server));
    server.addFeature(new LoggerBufferFeature(&server));
    server.addFeature(new LoggerFeature(&server, true));
    server.addFeature(new NonceFeature(&server));
    server.addFeature(new PageSizeFeature(&server));
    server.addFeature(new pregel::PregelFeature(&server));
    server.addFeature(new PrivilegeFeature(&server));
    server.addFeature(new RandomFeature(&server));
    server.addFeature(new QueryRegistryFeature(&server));
    server.addFeature(new SchedulerFeature(&server));
    server.addFeature(new ScriptFeature(&server, &ret));
    server.addFeature(new ServerFeature(&server, &ret));
    server.addFeature(new ServerIdFeature(&server));
    server.addFeature(new ShutdownFeature(&server, {"UnitTests", "Script"}));
    server.addFeature(new SslFeature(&server));
    server.addFeature(new StatisticsFeature(&server));
    server.addFeature(new TempFeature(&server, name));
    server.addFeature(new TransactionManagerFeature(&server));
    server.addFeature(new TraverserEngineRegistryFeature(&server));
    server.addFeature(new UnitTestsFeature(&server, &ret));
    server.addFeature(new UpgradeFeature(&server, &ret, nonServerFeatures));
    server.addFeature(new V8DealerFeature(&server));
    server.addFeature(new V8PlatformFeature(&server));
    server.addFeature(new VersionFeature(&server));
    server.addFeature(new ViewTypesFeature(&server));
    server.addFeature(new WorkMonitorFeature(&server));
    server.addFeature(new RocksDBOptionFeature(&server));

#ifdef ARANGODB_HAVE_FORK
    server.addFeature(new DaemonFeature(&server));
    server.addFeature(new SupervisorFeature(&server));
#endif

#ifdef _WIN32
    server.addFeature(new WindowsServiceFeature(&server));
#endif

#ifdef USE_ENTERPRISE
    setupServerEE(&server);
#else
    server.addFeature(new SslServerFeature(&server));
#endif

    // storage engines
    server.addFeature(new MMFilesEngine(&server));
    server.addFeature(new RocksDBEngine(&server));

    try {
      server.run(argc, argv);
      if (server.helpShown()) {
        // --help was displayed
        ret = EXIT_SUCCESS;
      }
    } catch (std::exception const& ex) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception: "
          << ex.what();
      ret = EXIT_FAILURE;
    } catch (...) {
      LOG_TOPIC(ERR, arangodb::Logger::FIXME)
          << "arangod terminated because of an exception of "
             "unknown type";
      ret = EXIT_FAILURE;
    }
    Logger::flush();
    return context.exit(ret);
  } catch (std::exception const& ex) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an exception: "
        << ex.what();
  } catch (...) {
    LOG_TOPIC(ERR, arangodb::Logger::FIXME)
        << "arangod terminated because of an xception of "
           "unknown type";
  }
  exit(EXIT_FAILURE);
}

#if _WIN32
static int ARGC;
static char** ARGV;

static void WINAPI ServiceMain(DWORD dwArgc, LPSTR* lpszArgv) {
  if (!TRI_InitWindowsEventLog()) {
    return;
  }
  // register the service ctrl handler,  lpszArgv[0] contains service name
  ServiceStatus =
      RegisterServiceCtrlHandlerA(lpszArgv[0], (LPHANDLER_FUNCTION)ServiceCtrl);

  // set start pending
  SetServiceStatus(SERVICE_START_PENDING, 0, 1, 10000);

  ArangoGlobalContext context(ARGC, ARGV, SBIN_DIRECTORY);
  runServer(ARGC, ARGV, context);

  // service has stopped
  SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0, 0);
  TRI_CloseWindowsEventlog();
}

#endif

int main(int argc, char* argv[]) {
#if _WIN32
  if (argc > 1 && TRI_EqualString("--start-service", argv[1])) {
    ARGC = argc;
    ARGV = argv;

    SERVICE_TABLE_ENTRY ste[] = {
      {TEXT(""), (LPSERVICE_MAIN_FUNCTION)ServiceMain}, {nullptr, nullptr}};

    if (!StartServiceCtrlDispatcher(ste)) {
      std::cerr << "FATAL: StartServiceCtrlDispatcher has failed with "
                << GetLastError() << std::endl;
      exit(EXIT_FAILURE);
    }
    return 0;
  }
#endif
  ArangoGlobalContext context(argc, argv, SBIN_DIRECTORY);
  return runServer(argc, argv, context);
}
<|endoftext|>


<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    uiserver/signencryptwizard.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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 2 of the License, or
    (at your option) any later version.

    Kleopatra 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 this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "signencryptwizard.h"

#include "certificateresolver.h"
#include "objectspage.h"
#include "recipientresolvepage.h"
#include "signerresolvepage.h"
#include "resultdisplaywidget.h"
#include "wizardresultpage.h"
#include "task.h"
#include "kleo-assuan.h"

#include <utils/stl_util.h>

#include <kmime/kmime_header_parsing.h>

#include <gpgme++/key.h>

#include <KLocale>
#include <KPushButton>

#include <QFileInfo>
#include <QTimer>
#include <QWizard>

#include <boost/bind.hpp>

using namespace Kleo;
using namespace boost;
using namespace GpgME;
using namespace KMime::Types;

class SignEncryptWizard::Private {
    friend class ::Kleo::SignEncryptWizard;
    SignEncryptWizard * q;
public:
    explicit Private( SignEncryptWizard * qq );
    ~Private();

    void selectedProtocolChanged();
    void setCommitPage( Page page );

private:
    std::vector<Mailbox> recipients;
    Mode mode;

    RecipientResolvePage * recipientResolvePage;
    SignerResolvePage * signerResolvePage;
    Kleo::ObjectsPage * objectsPage;
    WizardResultPage * resultPage;
};

SignEncryptWizard::Private::Private( SignEncryptWizard * qq )
    : q( qq ),
      mode( EncryptOrSignFiles ),
      recipientResolvePage( new RecipientResolvePage ),
      signerResolvePage( new SignerResolvePage ),
      objectsPage( new Kleo::ObjectsPage ),
      resultPage( new WizardResultPage )
{
    q->connect( recipientResolvePage, SIGNAL( selectedProtocolChanged() ),
             q, SLOT( selectedProtocolChanged() ) );
    q->setPage( SignEncryptWizard::ResolveSignerPage, signerResolvePage );
    q->setPage( SignEncryptWizard::ObjectsPage, objectsPage );
    q->setPage( SignEncryptWizard::ResolveRecipientsPage, recipientResolvePage );
    q->setPage( SignEncryptWizard::ResultPage, resultPage );
    q->resize( QSize( 640, 480 ).expandedTo( q->sizeHint() ) );
}

void SignEncryptWizard::Private::selectedProtocolChanged()
{
    //TODO: this slot is a temporary workaround to keep the
    // recipient resolving in the wizard for now. should be
    // changed when reworking the recipientresolvepage
    const std::vector< std::vector<Key> > keys = CertificateResolver::resolveRecipients( recipients, q->selectedProtocol() );
    assuan_assert( !keys.empty() );
    assuan_assert( keys.size() == static_cast<size_t>( recipients.size() ) );

    for ( unsigned int i = 0, end = keys.size() ; i < end ; ++i ) {
        RecipientResolveWidget * const rr = recipientResolvePage->recipientResolveWidget( i );
        assuan_assert( rr );
        rr->setIdentifier( recipients[i].prettyAddress() );
        rr->setCertificates( keys[i] );
    }

}

void SignEncryptWizard::onNext( int currentId )
{
    if ( currentId == ResolveRecipientsPage )
        QTimer::singleShot( 0, this, SIGNAL( recipientsResolved() ) );
    if ( currentId == ResolveSignerPage )
        QTimer::singleShot( 0, this, SIGNAL( signersResolved() ) );
    if ( currentId == ObjectsPage )
        QTimer::singleShot( 0, this, SIGNAL( objectsResolved() ) );
}

SignEncryptWizard::Private::~Private() {}

SignEncryptWizard::SignEncryptWizard( QWidget * p, Qt::WindowFlags f )
    : Wizard( p, f ), d( new Private( this ) )
{
}

SignEncryptWizard::~SignEncryptWizard() {}

void SignEncryptWizard::Private::setCommitPage( Page page )
{
    q->page( ResolveSignerPage )->setCommitPage( false );
    q->page( ResolveRecipientsPage )->setCommitPage( false );
    q->page( ObjectsPage )->setCommitPage( false );
    q->page( ResultPage )->setCommitPage( false );
    q->page( page )->setCommitPage( true );
}

void SignEncryptWizard::setMode( Mode mode ) {

    std::vector<int> pageOrder;
    switch ( mode )
    {
    case EncryptEMail:
        pageOrder.push_back( ResolveRecipientsPage );
        pageOrder.push_back( ResultPage );
        d->setCommitPage( ResolveRecipientsPage );
        break;
    case SignEMail:
        pageOrder.push_back( ResolveSignerPage );
        pageOrder.push_back( ResultPage );
        d->setCommitPage( ResolveSignerPage );
        break;
    case SignOrEncryptFiles:
        pageOrder.push_back( ResolveSignerPage );
        pageOrder.push_back( ObjectsPage );
        pageOrder.push_back( ResolveRecipientsPage );
        pageOrder.push_back( ResultPage );
        d->setCommitPage( ResolveRecipientsPage );
        break;
    default:
        assuan_assert( !"Case not yet implemented" );
        break;
    }
    setPageOrder( pageOrder );
    setCurrentPage( pageOrder.front() );
    d->mode = mode;
}

void SignEncryptWizard::setPresetProtocol( Protocol proto ) {
    assuan_assert( d->mode == EncryptEMail || d->mode == SignEMail || d->mode == SignOrEncryptFiles );
    d->signerResolvePage->setProtocol( proto );
    d->recipientResolvePage->setPresetProtocol( proto );
}

GpgME::Protocol SignEncryptWizard::selectedProtocol() const
{
    return d->recipientResolvePage->selectedProtocol();
}

GpgME::Protocol SignEncryptWizard::presetProtocol() const
{
    return d->recipientResolvePage->presetProtocol();
}

void SignEncryptWizard::setEncryptionSelected( bool selected )
{
    d->signerResolvePage->setEncryptionSelected( selected );
}

void SignEncryptWizard::setSigningSelected( bool selected )
{
    d->signerResolvePage->setSigningSelected( selected );
}

bool SignEncryptWizard::isSigningUserMutable() const
{
    return d->signerResolvePage->isSigningUserMutable();
}

void SignEncryptWizard::setSigningUserMutable( bool isMutable )
{
    d->signerResolvePage->setSigningUserMutable( isMutable );
}

bool SignEncryptWizard::isEncryptionUserMutable() const
{
    return d->signerResolvePage->isEncryptionUserMutable();
}

bool SignEncryptWizard::isMultipleProtocolsAllowed() const
{
    return d->recipientResolvePage->isMultipleProtocolsAllowed();
}

void SignEncryptWizard::setMultipleProtocolsAllowed( bool allowed )
{
    d->recipientResolvePage->setMultipleProtocolsAllowed( allowed );
}

void SignEncryptWizard::setEncryptionUserMutable( bool isMutable )
{
    d->signerResolvePage->setEncryptionUserMutable( isMutable );
}

void SignEncryptWizard::setFiles( const QStringList & files ) {
    d->objectsPage->setFiles( files );
}

QFileInfoList SignEncryptWizard::resolvedFiles() const {
    const QStringList files = d->objectsPage->files();
    QFileInfoList infos;
    foreach ( const QString& i, files )
        infos.push_back( QFileInfo( i ) );
    return infos;
}

bool SignEncryptWizard::signingSelected() const {
    return d->signerResolvePage->signingSelected();
}

bool SignEncryptWizard::encryptionSelected() const {
    return d->signerResolvePage->encryptionSelected();
}

void SignEncryptWizard::setRecipients( const std::vector<Mailbox> & recipients ) {
    assuan_assert( d->mode == EncryptEMail );
    d->recipients = recipients;
    d->recipientResolvePage->ensureIndexAvailable( recipients.size() - 1 );
    d->selectedProtocolChanged();
}

void SignEncryptWizard::setSignersAndCandidates( const std::vector<Mailbox> & signers, const std::vector< std::vector<Key> > & keys ) {;
    assuan_assert( d->mode == SignEMail );
    d->signerResolvePage->setSignersAndCandidates( signers, keys );
}

void SignEncryptWizard::connectTask( const shared_ptr<Task> & task, unsigned int idx ) {
    assuan_assert( task );
    ResultDisplayWidget* const item = new ResultDisplayWidget;
    item->setLabel( task->label() );
    connect( task.get(), SIGNAL( progress( QString, int, int ) ),
             item, SLOT( setProgress( QString, int, int ) ) );
    connect( task.get(), SIGNAL( error( int, QString ) ),
             item, SLOT( setError( int, QString ) ) );
    connect( task.get(), SIGNAL(result( boost::shared_ptr<const Kleo::Task::Result> ) ),
             item, SLOT( setResult( boost::shared_ptr<const Kleo::Task::Result> ) ) );
    d->resultPage->addResultItem( item );
}

std::vector<Key> SignEncryptWizard::resolvedCertificates() const {
    std::vector<Key> result;
    for ( unsigned int i = 0, end = d->recipientResolvePage->numRecipientResolveWidgets() ; i < end ; ++i )
        result.push_back( d->recipientResolvePage->recipientResolveWidget( i )->chosenCertificate() );
    return result;
}

std::vector<Key> SignEncryptWizard::resolvedSigners() const {
    return d->signerResolvePage->resolvedSigners();
}

#include "moc_signencryptwizard.cpp"
<commit_msg>SVN_SILENT includes not needed<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    uiserver/signencryptwizard.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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 2 of the License, or
    (at your option) any later version.

    Kleopatra 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 this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "signencryptwizard.h"

#include "certificateresolver.h"
#include "objectspage.h"
#include "recipientresolvepage.h"
#include "signerresolvepage.h"
#include "resultdisplaywidget.h"
#include "wizardresultpage.h"
#include "task.h"
#include "kleo-assuan.h"

#include <utils/stl_util.h>

#include <kmime/kmime_header_parsing.h>

#include <gpgme++/key.h>

#include <KLocale>

#include <QFileInfo>
#include <QTimer>

#include <boost/bind.hpp>

using namespace Kleo;
using namespace boost;
using namespace GpgME;
using namespace KMime::Types;

class SignEncryptWizard::Private {
    friend class ::Kleo::SignEncryptWizard;
    SignEncryptWizard * q;
public:
    explicit Private( SignEncryptWizard * qq );
    ~Private();

    void selectedProtocolChanged();
    void setCommitPage( Page page );

private:
    std::vector<Mailbox> recipients;
    Mode mode;

    RecipientResolvePage * recipientResolvePage;
    SignerResolvePage * signerResolvePage;
    Kleo::ObjectsPage * objectsPage;
    WizardResultPage * resultPage;
};

SignEncryptWizard::Private::Private( SignEncryptWizard * qq )
    : q( qq ),
      mode( EncryptOrSignFiles ),
      recipientResolvePage( new RecipientResolvePage ),
      signerResolvePage( new SignerResolvePage ),
      objectsPage( new Kleo::ObjectsPage ),
      resultPage( new WizardResultPage )
{
    q->connect( recipientResolvePage, SIGNAL( selectedProtocolChanged() ),
             q, SLOT( selectedProtocolChanged() ) );
    q->setPage( SignEncryptWizard::ResolveSignerPage, signerResolvePage );
    q->setPage( SignEncryptWizard::ObjectsPage, objectsPage );
    q->setPage( SignEncryptWizard::ResolveRecipientsPage, recipientResolvePage );
    q->setPage( SignEncryptWizard::ResultPage, resultPage );
    q->resize( QSize( 640, 480 ).expandedTo( q->sizeHint() ) );
}

void SignEncryptWizard::Private::selectedProtocolChanged()
{
    //TODO: this slot is a temporary workaround to keep the
    // recipient resolving in the wizard for now. should be
    // changed when reworking the recipientresolvepage
    const std::vector< std::vector<Key> > keys = CertificateResolver::resolveRecipients( recipients, q->selectedProtocol() );
    assuan_assert( !keys.empty() );
    assuan_assert( keys.size() == static_cast<size_t>( recipients.size() ) );

    for ( unsigned int i = 0, end = keys.size() ; i < end ; ++i ) {
        RecipientResolveWidget * const rr = recipientResolvePage->recipientResolveWidget( i );
        assuan_assert( rr );
        rr->setIdentifier( recipients[i].prettyAddress() );
        rr->setCertificates( keys[i] );
    }

}

void SignEncryptWizard::onNext( int currentId )
{
    if ( currentId == ResolveRecipientsPage )
        QTimer::singleShot( 0, this, SIGNAL( recipientsResolved() ) );
    if ( currentId == ResolveSignerPage )
        QTimer::singleShot( 0, this, SIGNAL( signersResolved() ) );
    if ( currentId == ObjectsPage )
        QTimer::singleShot( 0, this, SIGNAL( objectsResolved() ) );
}

SignEncryptWizard::Private::~Private() {}

SignEncryptWizard::SignEncryptWizard( QWidget * p, Qt::WindowFlags f )
    : Wizard( p, f ), d( new Private( this ) )
{
}

SignEncryptWizard::~SignEncryptWizard() {}

void SignEncryptWizard::Private::setCommitPage( Page page )
{
    q->page( ResolveSignerPage )->setCommitPage( false );
    q->page( ResolveRecipientsPage )->setCommitPage( false );
    q->page( ObjectsPage )->setCommitPage( false );
    q->page( ResultPage )->setCommitPage( false );
    q->page( page )->setCommitPage( true );
}

void SignEncryptWizard::setMode( Mode mode ) {

    std::vector<int> pageOrder;
    switch ( mode )
    {
    case EncryptEMail:
        pageOrder.push_back( ResolveRecipientsPage );
        pageOrder.push_back( ResultPage );
        d->setCommitPage( ResolveRecipientsPage );
        break;
    case SignEMail:
        pageOrder.push_back( ResolveSignerPage );
        pageOrder.push_back( ResultPage );
        d->setCommitPage( ResolveSignerPage );
        break;
    case SignOrEncryptFiles:
        pageOrder.push_back( ResolveSignerPage );
        pageOrder.push_back( ObjectsPage );
        pageOrder.push_back( ResolveRecipientsPage );
        pageOrder.push_back( ResultPage );
        d->setCommitPage( ResolveRecipientsPage );
        break;
    default:
        assuan_assert( !"Case not yet implemented" );
        break;
    }
    setPageOrder( pageOrder );
    setCurrentPage( pageOrder.front() );
    d->mode = mode;
}

void SignEncryptWizard::setPresetProtocol( Protocol proto ) {
    assuan_assert( d->mode == EncryptEMail || d->mode == SignEMail || d->mode == SignOrEncryptFiles );
    d->signerResolvePage->setProtocol( proto );
    d->recipientResolvePage->setPresetProtocol( proto );
}

GpgME::Protocol SignEncryptWizard::selectedProtocol() const
{
    return d->recipientResolvePage->selectedProtocol();
}

GpgME::Protocol SignEncryptWizard::presetProtocol() const
{
    return d->recipientResolvePage->presetProtocol();
}

void SignEncryptWizard::setEncryptionSelected( bool selected )
{
    d->signerResolvePage->setEncryptionSelected( selected );
}

void SignEncryptWizard::setSigningSelected( bool selected )
{
    d->signerResolvePage->setSigningSelected( selected );
}

bool SignEncryptWizard::isSigningUserMutable() const
{
    return d->signerResolvePage->isSigningUserMutable();
}

void SignEncryptWizard::setSigningUserMutable( bool isMutable )
{
    d->signerResolvePage->setSigningUserMutable( isMutable );
}

bool SignEncryptWizard::isEncryptionUserMutable() const
{
    return d->signerResolvePage->isEncryptionUserMutable();
}

bool SignEncryptWizard::isMultipleProtocolsAllowed() const
{
    return d->recipientResolvePage->isMultipleProtocolsAllowed();
}

void SignEncryptWizard::setMultipleProtocolsAllowed( bool allowed )
{
    d->recipientResolvePage->setMultipleProtocolsAllowed( allowed );
}

void SignEncryptWizard::setEncryptionUserMutable( bool isMutable )
{
    d->signerResolvePage->setEncryptionUserMutable( isMutable );
}

void SignEncryptWizard::setFiles( const QStringList & files ) {
    d->objectsPage->setFiles( files );
}

QFileInfoList SignEncryptWizard::resolvedFiles() const {
    const QStringList files = d->objectsPage->files();
    QFileInfoList infos;
    foreach ( const QString& i, files )
        infos.push_back( QFileInfo( i ) );
    return infos;
}

bool SignEncryptWizard::signingSelected() const {
    return d->signerResolvePage->signingSelected();
}

bool SignEncryptWizard::encryptionSelected() const {
    return d->signerResolvePage->encryptionSelected();
}

void SignEncryptWizard::setRecipients( const std::vector<Mailbox> & recipients ) {
    assuan_assert( d->mode == EncryptEMail );
    d->recipients = recipients;
    d->recipientResolvePage->ensureIndexAvailable( recipients.size() - 1 );
    d->selectedProtocolChanged();
}

void SignEncryptWizard::setSignersAndCandidates( const std::vector<Mailbox> & signers, const std::vector< std::vector<Key> > & keys ) {;
    assuan_assert( d->mode == SignEMail );
    d->signerResolvePage->setSignersAndCandidates( signers, keys );
}

void SignEncryptWizard::connectTask( const shared_ptr<Task> & task, unsigned int idx ) {
    assuan_assert( task );
    ResultDisplayWidget* const item = new ResultDisplayWidget;
    item->setLabel( task->label() );
    connect( task.get(), SIGNAL( progress( QString, int, int ) ),
             item, SLOT( setProgress( QString, int, int ) ) );
    connect( task.get(), SIGNAL( error( int, QString ) ),
             item, SLOT( setError( int, QString ) ) );
    connect( task.get(), SIGNAL(result( boost::shared_ptr<const Kleo::Task::Result> ) ),
             item, SLOT( setResult( boost::shared_ptr<const Kleo::Task::Result> ) ) );
    d->resultPage->addResultItem( item );
}

std::vector<Key> SignEncryptWizard::resolvedCertificates() const {
    std::vector<Key> result;
    for ( unsigned int i = 0, end = d->recipientResolvePage->numRecipientResolveWidgets() ; i < end ; ++i )
        result.push_back( d->recipientResolvePage->recipientResolveWidget( i )->chosenCertificate() );
    return result;
}

std::vector<Key> SignEncryptWizard::resolvedSigners() const {
    return d->signerResolvePage->resolvedSigners();
}

#include "moc_signencryptwizard.cpp"
<|endoftext|>