<commit_before>/*

    Graphics File Loader: a test program for csgfxldr library
    Copyright (C) 2000 Andrew Zabolotny <bit@eltech.ru>

    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.

*/

#define SYSDEF_PATH
#define SYSDEF_GETOPT
#include "sysdef.h"
#include "csgfxldr/csimage.h"
#include "csgfxldr/pngsave.h"

#include <string.h>

char *programversion = "0.0.1";
char *programname;

/*

  NOTE: If your Losing Operating System {tm} (R) does not have getopt_long,
  please use the one in support/gnu instead. Please don't comment out blocks
  of code, dont #ifdef and so on. It is ugly.

*/

static struct option long_options[] =
{
  {"help", no_argument, 0, 'h'},
  {"display", optional_argument, 0, 'D'},
  {"dither", no_argument, 0, 'd'},
  {"scale", required_argument, 0, 's'},
  {"mipmap", required_argument, 0, 'm'},
  {"transp", required_argument, 0, 't'},
  {"paletted", no_argument, 0, '8'},
  {"truecolor", no_argument, 0, 'c'},
  {"verbose", no_argument, 0, 'v'},
  {"version", no_argument, 0, 'V'},
  {0, no_argument, 0, 0}
};

static struct
{
  bool verbose;
  bool save;
  bool display;
  bool dither;
  bool paletted;
  bool truecolor;
  int scaleX, scaleY;
  int displayW, displayH;
  int mipmap;
  bool transp;
} opt =
{
  false,
  true,
  false,
  false,
  false,
  false,
  0, 0,
  79, 24,
  -1,
  false
};
// Dont move inside the struct!
static RGBPixel transpcolor;

static int display_help ()
{
  printf ("Crystal Space Graphics File Loader test application v%s\n", programversion);
  printf ("Copyright (C) 2000 Andrew Zabolotny\n\n");
  printf ("Usage: %s {option/s} [image file] [...]\n\n", programname);
  printf ("  -D   --display{=#,#} Display the image in ASCII format :-)\n");
  printf ("  -d   --dither        Apply Floyd-Steinberg dithering when reducing to 8 bpp\n");
  printf ("  -s   --scale=#,#     Re-scale the image to given size #\n");
  printf ("  -m   --mipmap=#      Create mipmap level # (=0,1,2,3) from image\n");
  printf ("  -t   --transp=#,#,#  Treat color (R,G,B) as transparent\n");
  printf ("  -8   --paletted      Convert image to 8 bits-per-pixel paletted format\n");
  printf ("  -c   --truecolor     Convert image to truecolor format\n");
  printf ("  -h   --help          Display this help text\n");
  printf ("  -v   --verbose       Comment on what's happening\n");
  printf ("  -V   --version       Display program version\n");
  return 1;
}

#if 0
// PNM is a very simple format that is handy for quick-and-dirty programs.
// Many image processing programs understands it...
static bool SavePNM (const char *fname, void *image, int w, int h, bool rgb)
{
  FILE *f = fopen (fname, "wb");
  if (!f)
  {
    fprintf (stderr, "%s: cannot open output file %s\n", programname, fname);
    return false;
  }
  char header [100];
  sprintf (header, "P%c\n%d %d\n%d\n", rgb ? '6' : '5', w, h, 255);
  fwrite (header, 1, strlen (header), f);
  if (rgb)
    for (int i = w * h; i > 0; i--)
    {
      fwrite (image, 1, 3, f);
      image = ((RGBPixel *)image) + 1;
    }
  else
    fwrite (image, 1, w * h, f);
  fclose (f);
  return true;
}
#endif

static bool process_file (const char *fname)
{
  printf ("Loading file %s\n", fname);

  FILE *f = fopen (fname, "rb");
  if (!f)
  {
    printf ("%s: cannot open file %s\n", programname, fname);
    return false;
  }

  fseek (f, 0, SEEK_END);
  size_t fsize = ftell (f);
  fseek (f, 0, SEEK_SET);

  if (opt.verbose)
    printf ("Reading %ld bytes from file\n", fsize);

  UByte *buffer = new UByte [fsize];
  if (fread (buffer, 1, fsize, f) < fsize)
  {
    printf ("%s: unexpected EOF while reading file %s\n", programname, fname);
    return false;
  }

  fclose (f);

  int fmt;
  if (opt.paletted)
    fmt = CS_IMGFMT_PALETTED8;
  else if (opt.truecolor)
    fmt = CS_IMGFMT_TRUECOLOR;
  else
    fmt = CS_IMGFMT_ANY;

  iImage *ifile = csImageLoader::Load (buffer, fsize, fmt | CS_IMGFMT_ALPHA);
  delete [] buffer;
  if (!ifile)
  {
    printf ("%s: failed to recognise image format for %s\n", programname, fname);
    return false;
  }

  if (opt.verbose)
  {
    printf ("Image size: %d x %d pixels, %d bytes\n", ifile->GetWidth (),
      ifile->GetHeight (), ifile->GetSize ());
    int fmt = ifile->GetFormat ();
    printf ("Image format: %s, alpha channel: %s\n",
      (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_NONE ? "none" :
      (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_PALETTED8 ? "paletted, 256 colors" :
      (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR ? "truecolor" : "unknown",
      (fmt & CS_IMGFMT_ALPHA) ? "present" : "not present");
  }

  char suffix [20];
  suffix [0] = 0;

  if (opt.scaleX > 0 && opt.scaleY > 0)
  {
    printf ("Rescaling image to %d x %d\n", opt.scaleX, opt.scaleY);
    ifile->Rescale (opt.scaleX, opt.scaleY);
    sprintf (strchr (suffix, 0), "-s%dx%d", opt.scaleX, opt.scaleY);
  }

  if (opt.mipmap >= 0)
  {
    printf ("Creating mipmap level %d from image\n", opt.mipmap);
    iImage *ifile2 = ifile->MipMap (opt.mipmap,
      opt.transp ? &transpcolor : NULL);
    ifile->DecRef ();
    ifile = ifile2;
    sprintf (strchr (suffix, 0), "-m%d", opt.mipmap);
  }

  if (opt.save)
  {
    char outname [MAXPATHLEN + 1];
    strcpy (outname, fname);
    char *eol = strchr (outname, 0);
    while (eol > outname && *eol != '.') eol--;
    if (eol == outname) eol = strchr (outname, 0);
    strcpy (eol, suffix);
    strcat (eol, ".png");
    printf ("Saving output file %s\n", outname);

#if 1
    if (!csSavePNG (outname, ifile))
      return false;
#else
    if (!SavePNM (outname, ifile->GetImageData (), ifile->GetWidth (), ifile->GetHeight (),
         (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR))
      return false;
#endif
  }

  if (opt.display)
  {
    static char imgchr [] = " .,;+*oO";
    ifile->Rescale (opt.displayW, opt.displayH);
    RGBPixel *rgb;
    UByte *idx = NULL;
    bool truecolor = (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR;
    if (truecolor)
      rgb = (RGBPixel *)ifile->GetImageData ();
    else
    {
      idx = (UByte *)ifile->GetImageData ();
      rgb = ifile->GetPalette ();
    }
    for (int y = 0; y < opt.displayH; y++)
    {
      for (int x = 0; x < opt.displayW; x++)
      {
        RGBPixel &src = truecolor ? *rgb++ : rgb [*idx++];
        int gray = int (sqrt (src.red * src.red + src.green * src.green +
          src.blue * src.blue) * 8 / 442);
        putc (imgchr [gray], stdout);
      }
      putc ('\n', stdout);
    }
  }

  // Destroy the image object
  ifile->DecRef ();

  return true;
}

int main (int argc, char **argv)
{
#if defined (__EMX__)	// Expand wildcards on OS/2+GCC+EMX
  _wildcard (&argc, &argv);
#endif

  programname = argv [0];

  int c;
  while ((c = getopt_long (argc, argv, "8cd::s:m:t:hvV", long_options, NULL)) != EOF)
    switch (c)
    {
      case '?':
        // unknown option
        return -1;
      case '8':
        opt.paletted = true;
        break;
      case 'c':
        opt.truecolor = true;
        break;
      case 'd':
        opt.dither = true;
        break;
      case 'D':
        opt.save = false;
        opt.display = true;
        if (optarg &&
            sscanf (optarg, "%d,%d", &opt.displayW, &opt.displayH) != 2)
        {
          printf ("%s: expecting <width>,<height> after -d\n", programname);
          return -1;
        }
        break;
      case 's':
        if (sscanf (optarg, "%d,%d", &opt.scaleX, &opt.scaleY) != 2)
        {
          printf ("%s: expecting <width>,<height> after -s\n", programname);
          return -1;
        }
        break;
      case 't':
      {
        opt.transp = true;
        int r,g,b;
        if (sscanf (optarg, "%d,%d,%d", &r, &g, &b) != 3)
        {
          printf ("%s: expecting <R>,<G>,<B> after -t\n", programname);
          return -1;
        }
        transpcolor.red   = r > 255 ? 255 : r < 0 ? 0 : r;
        transpcolor.green = g > 255 ? 255 : g < 0 ? 0 : g;
        transpcolor.blue  = b > 255 ? 255 : b < 0 ? 0 : b;
        break;
      }
      case 'm':
        if (sscanf (optarg, "%d", &opt.mipmap) != 1)
        {
          printf ("%s: expecting <mipmap level> which is one of 0,1,2,3 after -m\n", programname);
          return -1;
        }
        if (opt.mipmap < 0 || opt.mipmap > 3)
        {
          printf ("%s: bad mipmap level (%d): should be one of 0,1,2,3\n", programname, opt.mipmap);
          return -1;
        }
        break;
      case 'h':
        return display_help ();
      case 'v':
        opt.verbose = true;
        break;
      case 'V':
        printf ("%s version %s\n\n", programname, programversion);
        printf ("This program is distributed in the hope that it will be useful,\n");
        printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
        printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
        printf ("GNU Library General Public License for more details.\n");
        return 0;
    } /* endswitch */

  if (optind >= argc)
    return display_help ();

  csImageLoader::SetDithering (opt.dither);

  for (; optind < argc; ++optind)
    if (!process_file (argv [optind]))
      return -1;

  return 0;
}
<commit_msg>%ld to %d placeholder change<commit_after>/*

    Graphics File Loader: a test program for csgfxldr library
    Copyright (C) 2000 Andrew Zabolotny <bit@eltech.ru>

    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.

*/

#define SYSDEF_PATH
#define SYSDEF_GETOPT
#include "sysdef.h"
#include "csgfxldr/csimage.h"
#include "csgfxldr/pngsave.h"

#include <string.h>

char *programversion = "0.0.1";
char *programname;

/*

  NOTE: If your Losing Operating System {tm} (R) does not have getopt_long,
  please use the one in support/gnu instead. Please don't comment out blocks
  of code, dont #ifdef and so on. It is ugly.

*/

static struct option long_options[] =
{
  {"help", no_argument, 0, 'h'},
  {"display", optional_argument, 0, 'D'},
  {"dither", no_argument, 0, 'd'},
  {"scale", required_argument, 0, 's'},
  {"mipmap", required_argument, 0, 'm'},
  {"transp", required_argument, 0, 't'},
  {"paletted", no_argument, 0, '8'},
  {"truecolor", no_argument, 0, 'c'},
  {"verbose", no_argument, 0, 'v'},
  {"version", no_argument, 0, 'V'},
  {0, no_argument, 0, 0}
};

static struct
{
  bool verbose;
  bool save;
  bool display;
  bool dither;
  bool paletted;
  bool truecolor;
  int scaleX, scaleY;
  int displayW, displayH;
  int mipmap;
  bool transp;
} opt =
{
  false,
  true,
  false,
  false,
  false,
  false,
  0, 0,
  79, 24,
  -1,
  false
};
// Dont move inside the struct!
static RGBPixel transpcolor;

static int display_help ()
{
  printf ("Crystal Space Graphics File Loader test application v%s\n", programversion);
  printf ("Copyright (C) 2000 Andrew Zabolotny\n\n");
  printf ("Usage: %s {option/s} [image file] [...]\n\n", programname);
  printf ("  -D   --display{=#,#} Display the image in ASCII format :-)\n");
  printf ("  -d   --dither        Apply Floyd-Steinberg dithering when reducing to 8 bpp\n");
  printf ("  -s   --scale=#,#     Re-scale the image to given size #\n");
  printf ("  -m   --mipmap=#      Create mipmap level # (=0,1,2,3) from image\n");
  printf ("  -t   --transp=#,#,#  Treat color (R,G,B) as transparent\n");
  printf ("  -8   --paletted      Convert image to 8 bits-per-pixel paletted format\n");
  printf ("  -c   --truecolor     Convert image to truecolor format\n");
  printf ("  -h   --help          Display this help text\n");
  printf ("  -v   --verbose       Comment on what's happening\n");
  printf ("  -V   --version       Display program version\n");
  return 1;
}

#if 0
// PNM is a very simple format that is handy for quick-and-dirty programs.
// Many image processing programs understands it...
static bool SavePNM (const char *fname, void *image, int w, int h, bool rgb)
{
  FILE *f = fopen (fname, "wb");
  if (!f)
  {
    fprintf (stderr, "%s: cannot open output file %s\n", programname, fname);
    return false;
  }
  char header [100];
  sprintf (header, "P%c\n%d %d\n%d\n", rgb ? '6' : '5', w, h, 255);
  fwrite (header, 1, strlen (header), f);
  if (rgb)
    for (int i = w * h; i > 0; i--)
    {
      fwrite (image, 1, 3, f);
      image = ((RGBPixel *)image) + 1;
    }
  else
    fwrite (image, 1, w * h, f);
  fclose (f);
  return true;
}
#endif

static bool process_file (const char *fname)
{
  printf ("Loading file %s\n", fname);

  FILE *f = fopen (fname, "rb");
  if (!f)
  {
    printf ("%s: cannot open file %s\n", programname, fname);
    return false;
  }

  fseek (f, 0, SEEK_END);
  size_t fsize = ftell (f);
  fseek (f, 0, SEEK_SET);

  if (opt.verbose)
    printf ("Reading %d bytes from file\n", fsize);

  UByte *buffer = new UByte [fsize];
  if (fread (buffer, 1, fsize, f) < fsize)
  {
    printf ("%s: unexpected EOF while reading file %s\n", programname, fname);
    return false;
  }

  fclose (f);

  int fmt;
  if (opt.paletted)
    fmt = CS_IMGFMT_PALETTED8;
  else if (opt.truecolor)
    fmt = CS_IMGFMT_TRUECOLOR;
  else
    fmt = CS_IMGFMT_ANY;

  iImage *ifile = csImageLoader::Load (buffer, fsize, fmt | CS_IMGFMT_ALPHA);
  delete [] buffer;
  if (!ifile)
  {
    printf ("%s: failed to recognise image format for %s\n", programname, fname);
    return false;
  }

  if (opt.verbose)
  {
    printf ("Image size: %d x %d pixels, %d bytes\n", ifile->GetWidth (),
      ifile->GetHeight (), ifile->GetSize ());
    int fmt = ifile->GetFormat ();
    printf ("Image format: %s, alpha channel: %s\n",
      (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_NONE ? "none" :
      (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_PALETTED8 ? "paletted, 256 colors" :
      (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR ? "truecolor" : "unknown",
      (fmt & CS_IMGFMT_ALPHA) ? "present" : "not present");
  }

  char suffix [20];
  suffix [0] = 0;

  if (opt.scaleX > 0 && opt.scaleY > 0)
  {
    printf ("Rescaling image to %d x %d\n", opt.scaleX, opt.scaleY);
    ifile->Rescale (opt.scaleX, opt.scaleY);
    sprintf (strchr (suffix, 0), "-s%dx%d", opt.scaleX, opt.scaleY);
  }

  if (opt.mipmap >= 0)
  {
    printf ("Creating mipmap level %d from image\n", opt.mipmap);
    iImage *ifile2 = ifile->MipMap (opt.mipmap,
      opt.transp ? &transpcolor : NULL);
    ifile->DecRef ();
    ifile = ifile2;
    sprintf (strchr (suffix, 0), "-m%d", opt.mipmap);
  }

  if (opt.save)
  {
    char outname [MAXPATHLEN + 1];
    strcpy (outname, fname);
    char *eol = strchr (outname, 0);
    while (eol > outname && *eol != '.') eol--;
    if (eol == outname) eol = strchr (outname, 0);
    strcpy (eol, suffix);
    strcat (eol, ".png");
    printf ("Saving output file %s\n", outname);

#if 1
    if (!csSavePNG (outname, ifile))
      return false;
#else
    if (!SavePNM (outname, ifile->GetImageData (), ifile->GetWidth (), ifile->GetHeight (),
         (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR))
      return false;
#endif
  }

  if (opt.display)
  {
    static char imgchr [] = " .,;+*oO";
    ifile->Rescale (opt.displayW, opt.displayH);
    RGBPixel *rgb;
    UByte *idx = NULL;
    bool truecolor = (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR;
    if (truecolor)
      rgb = (RGBPixel *)ifile->GetImageData ();
    else
    {
      idx = (UByte *)ifile->GetImageData ();
      rgb = ifile->GetPalette ();
    }
    for (int y = 0; y < opt.displayH; y++)
    {
      for (int x = 0; x < opt.displayW; x++)
      {
        RGBPixel &src = truecolor ? *rgb++ : rgb [*idx++];
        int gray = int (sqrt (src.red * src.red + src.green * src.green +
          src.blue * src.blue) * 8 / 442);
        putc (imgchr [gray], stdout);
      }
      putc ('\n', stdout);
    }
  }

  // Destroy the image object
  ifile->DecRef ();

  return true;
}

int main (int argc, char **argv)
{
#if defined (__EMX__)	// Expand wildcards on OS/2+GCC+EMX
  _wildcard (&argc, &argv);
#endif

  programname = argv [0];

  int c;
  while ((c = getopt_long (argc, argv, "8cd::s:m:t:hvV", long_options, NULL)) != EOF)
    switch (c)
    {
      case '?':
        // unknown option
        return -1;
      case '8':
        opt.paletted = true;
        break;
      case 'c':
        opt.truecolor = true;
        break;
      case 'd':
        opt.dither = true;
        break;
      case 'D':
        opt.save = false;
        opt.display = true;
        if (optarg &&
            sscanf (optarg, "%d,%d", &opt.displayW, &opt.displayH) != 2)
        {
          printf ("%s: expecting <width>,<height> after -d\n", programname);
          return -1;
        }
        break;
      case 's':
        if (sscanf (optarg, "%d,%d", &opt.scaleX, &opt.scaleY) != 2)
        {
          printf ("%s: expecting <width>,<height> after -s\n", programname);
          return -1;
        }
        break;
      case 't':
      {
        opt.transp = true;
        int r,g,b;
        if (sscanf (optarg, "%d,%d,%d", &r, &g, &b) != 3)
        {
          printf ("%s: expecting <R>,<G>,<B> after -t\n", programname);
          return -1;
        }
        transpcolor.red   = r > 255 ? 255 : r < 0 ? 0 : r;
        transpcolor.green = g > 255 ? 255 : g < 0 ? 0 : g;
        transpcolor.blue  = b > 255 ? 255 : b < 0 ? 0 : b;
        break;
      }
      case 'm':
        if (sscanf (optarg, "%d", &opt.mipmap) != 1)
        {
          printf ("%s: expecting <mipmap level> which is one of 0,1,2,3 after -m\n", programname);
          return -1;
        }
        if (opt.mipmap < 0 || opt.mipmap > 3)
        {
          printf ("%s: bad mipmap level (%d): should be one of 0,1,2,3\n", programname, opt.mipmap);
          return -1;
        }
        break;
      case 'h':
        return display_help ();
      case 'v':
        opt.verbose = true;
        break;
      case 'V':
        printf ("%s version %s\n\n", programname, programversion);
        printf ("This program is distributed in the hope that it will be useful,\n");
        printf ("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
        printf ("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n");
        printf ("GNU Library General Public License for more details.\n");
        return 0;
    } /* endswitch */

  if (optind >= argc)
    return display_help ();

  csImageLoader::SetDithering (opt.dither);

  for (; optind < argc; ++optind)
    if (!process_file (argv [optind]))
      return -1;

  return 0;
}
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "condor_classad.h"
#include "condor_config.h"
#include "condor_qmgr.h"
#include "match_prefix.h"
#include "sig_install.h"
#include "get_daemon_name.h"
#include "condor_attributes.h"
#include "condor_distribution.h"
#include "daemon.h"
#include "dc_schedd.h"
#include "MyString.h"

void
usage(char name[])
{
	fprintf(stderr, "Usage: %s [-n schedd-name] [-pool pool-name] { cluster | cluster.proc | owner | -constraint constraint } attribute-name attribute-value ...\n", name);
	exit(1);
}

bool
ProtectedAttribute(char attr[])
{
	return (strcmp(attr, ATTR_OWNER) == 0) ||
		(strcmp(attr, ATTR_CLUSTER_ID) == 0) ||
		(strcmp(attr, ATTR_PROC_ID) == 0) ||
		(strcmp(attr, ATTR_MY_TYPE) == 0) ||
		(strcmp(attr, ATTR_TARGET_TYPE) == 0) ||
		(strcmp(attr, ATTR_JOB_STATUS) == 0);
}

int
main(int argc, char *argv[])
{
	MyString constraint;
	Qmgr_connection *q;
	int nextarg = 1, cluster, proc;
	bool UseConstraint = false;
	MyString schedd_name;
	MyString pool_name;

	myDistro->Init( argc, argv );
	config();

#if !defined(WIN32)
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	if (argc < 2) {
		usage(argv[0]);
	}

	// if it is present, it must be first
	if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'n') {
		nextarg++;
		// use the given name as the schedd name to connect to
		if (argc <= nextarg) {
			fprintf(stderr, "%s: -n requires another argument\n",
					argv[0]);
			exit(1);
		}
		schedd_name = argv[nextarg];
		nextarg++;
	}

	if (argc <= nextarg) {
		usage(argv[0]);
	}

	// if it is present, it must be just after -n flag
	if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'p') {
		nextarg++;
		if (argc <= nextarg) {
			fprintf(stderr, "%s: -pool requires another argument\n",
					argv[0]);
			exit(1);
		}
		pool_name = argv[nextarg];
		nextarg++;
	}

	DCSchedd schedd(schedd_name.GetCStr(), pool_name.GetCStr());
	if ( schedd.locate() == false ) {
		if (schedd_name == "") {
			fprintf( stderr, "%s: ERROR: Can't find address of local schedd\n",
				argv[0] );
			exit(1);
		}

		if (pool_name == "") {
			fprintf( stderr, "%s: No such schedd named %s in local pool\n",
				argv[0], schedd_name.Value() );
		} else {
			fprintf( stderr, "%s: No such schedd named %s in "
				"pool %s\n",
				argv[0], schedd_name.Value(), pool_name.Value() );
		}
		exit(1);
	}

	// Open job queue
	q = ConnectQ( schedd.addr() );
	if( !q ) {
		fprintf( stderr, "Failed to connect to queue manager %s\n",
				 schedd.addr() );
		exit(1);
	}

	if (argc <= nextarg) {
		usage(argv[0]);
	}

	if (match_prefix(argv[nextarg], "-constraint")) {
		nextarg++;
		if (argc <= nextarg) {
			usage(argv[0]);
		}
		constraint = argv[nextarg];
		nextarg++;
		UseConstraint = true;
	} else if (isdigit(argv[nextarg][0])) {
		char *tmp;
		cluster = strtol(argv[nextarg], &tmp, 10);
		if (cluster <= 0) {
			fprintf( stderr, "Invalid cluster # from %s.\n", argv[nextarg]);
			exit(1);
		}
		if (*tmp == '.') {
			proc = strtol(tmp + 1, &tmp, 10);
			if (cluster <= 0) {
				fprintf( stderr, "Invalid proc # from %s.\n", argv[nextarg]);
				exit(1);
			}
			UseConstraint = false;
		} else {
			constraint.sprintf("(%s == %d)", ATTR_CLUSTER_ID, cluster);
			UseConstraint = true;
		}
		nextarg++;
	} else {
		constraint.sprintf("(%s == \"%s\")", ATTR_OWNER, argv[nextarg]);
		nextarg++;
		UseConstraint = true;
	}

	if (argc <= nextarg) {
		usage(argv[0]);
	}

	for (; nextarg < argc; nextarg += 2) {
		if (argc <= nextarg+1) {
			usage(argv[0]);
		}
		if (ProtectedAttribute(argv[nextarg])) {
			fprintf(stderr, "Update of attribute \"%s\" is not allowed.\n",
					argv[nextarg]);
			exit(1);
		}
		if (UseConstraint) {
			if (SetAttributeByConstraint(constraint.Value(), argv[nextarg],
										 argv[nextarg+1]) < 0) {
				fprintf(stderr,
						"Failed to set attribute \"%s\" by constraint: %s\n",
						argv[nextarg], constraint.Value());
				exit(1);
			}
		} else {
			if (SetAttribute(cluster, proc, argv[nextarg],
							 argv[nextarg+1]) < 0) {
				fprintf(stderr,
						"Failed to set attribute \"%s\" for job %d.%d.\n",
						argv[nextarg], cluster, proc);
				exit(1);
			}
		}
		printf("Set attribute \"%s\".\n", argv[nextarg]);
	}

	if (!DisconnectQ(q)) {
		fprintf(stderr,
				"Queue transaction failed.  No attributes were set.\n");
		exit(1);
	}

	return 0;
}

#include "daemon_core_stubs.h"
<commit_msg>added support for the "-debug" option to condor_qedit.<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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 "condor_common.h"
#include "condor_classad.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_qmgr.h"
#include "match_prefix.h"
#include "sig_install.h"
#include "get_daemon_name.h"
#include "condor_attributes.h"
#include "condor_distribution.h"
#include "daemon.h"
#include "dc_schedd.h"
#include "MyString.h"

void
usage(char name[])
{
	fprintf(stderr, "Usage: %s [-debug] [-n schedd-name] [-pool pool-name] { cluster | cluster.proc | owner | -constraint constraint } attribute-name attribute-value ...\n", name);
	exit(1);
}

bool
ProtectedAttribute(char attr[])
{
	return (strcmp(attr, ATTR_OWNER) == 0) ||
		(strcmp(attr, ATTR_CLUSTER_ID) == 0) ||
		(strcmp(attr, ATTR_PROC_ID) == 0) ||
		(strcmp(attr, ATTR_MY_TYPE) == 0) ||
		(strcmp(attr, ATTR_TARGET_TYPE) == 0) ||
		(strcmp(attr, ATTR_JOB_STATUS) == 0);
}

int
main(int argc, char *argv[])
{
	MyString constraint;
	Qmgr_connection *q;
	int nextarg = 1, cluster, proc;
	bool UseConstraint = false;
	MyString schedd_name;
	MyString pool_name;

	myDistro->Init( argc, argv );
	config();

#if !defined(WIN32)
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	if (argc < 2) {
		usage(argv[0]);
	}

	// if -debug is present, it must be first. sigh.
	if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'd') {
		// output dprintf messages to stderror at TOOL_DEBUG level
		Termlog = 1;
		dprintf_config ("TOOL");
		nextarg++;
	}

	// if it is present, it must be first after debug.
	if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'n') {
		nextarg++;
		// use the given name as the schedd name to connect to
		if (argc <= nextarg) {
			fprintf(stderr, "%s: -n requires another argument\n",
					argv[0]);
			exit(1);
		}
		schedd_name = argv[nextarg];
		nextarg++;
	}

	if (argc <= nextarg) {
		usage(argv[0]);
	}

	// if it is present, it must be just after -n flag
	if (argv[nextarg][0] == '-' && argv[nextarg][1] == 'p') {
		nextarg++;
		if (argc <= nextarg) {
			fprintf(stderr, "%s: -pool requires another argument\n",
					argv[0]);
			exit(1);
		}
		pool_name = argv[nextarg];
		nextarg++;
	}

	DCSchedd schedd(schedd_name.GetCStr(), pool_name.GetCStr());
	if ( schedd.locate() == false ) {
		if (schedd_name == "") {
			fprintf( stderr, "%s: ERROR: Can't find address of local schedd\n",
				argv[0] );
			exit(1);
		}

		if (pool_name == "") {
			fprintf( stderr, "%s: No such schedd named %s in local pool\n",
				argv[0], schedd_name.Value() );
		} else {
			fprintf( stderr, "%s: No such schedd named %s in "
				"pool %s\n",
				argv[0], schedd_name.Value(), pool_name.Value() );
		}
		exit(1);
	}

	// Open job queue
	q = ConnectQ( schedd.addr() );
	if( !q ) {
		fprintf( stderr, "Failed to connect to queue manager %s\n",
				 schedd.addr() );
		exit(1);
	}

	if (argc <= nextarg) {
		usage(argv[0]);
	}

	if (match_prefix(argv[nextarg], "-constraint")) {
		nextarg++;
		if (argc <= nextarg) {
			usage(argv[0]);
		}
		constraint = argv[nextarg];
		nextarg++;
		UseConstraint = true;
	} else if (isdigit(argv[nextarg][0])) {
		char *tmp;
		cluster = strtol(argv[nextarg], &tmp, 10);
		if (cluster <= 0) {
			fprintf( stderr, "Invalid cluster # from %s.\n", argv[nextarg]);
			exit(1);
		}
		if (*tmp == '.') {
			proc = strtol(tmp + 1, &tmp, 10);
			if (cluster <= 0) {
				fprintf( stderr, "Invalid proc # from %s.\n", argv[nextarg]);
				exit(1);
			}
			UseConstraint = false;
		} else {
			constraint.sprintf("(%s == %d)", ATTR_CLUSTER_ID, cluster);
			UseConstraint = true;
		}
		nextarg++;
	} else {
		constraint.sprintf("(%s == \"%s\")", ATTR_OWNER, argv[nextarg]);
		nextarg++;
		UseConstraint = true;
	}

	if (argc <= nextarg) {
		usage(argv[0]);
	}

	for (; nextarg < argc; nextarg += 2) {
		if (argc <= nextarg+1) {
			usage(argv[0]);
		}
		if (ProtectedAttribute(argv[nextarg])) {
			fprintf(stderr, "Update of attribute \"%s\" is not allowed.\n",
					argv[nextarg]);
			exit(1);
		}
		if (UseConstraint) {
			if (SetAttributeByConstraint(constraint.Value(), argv[nextarg],
										 argv[nextarg+1]) < 0) {
				fprintf(stderr,
						"Failed to set attribute \"%s\" by constraint: %s\n",
						argv[nextarg], constraint.Value());
				exit(1);
			}
		} else {
			if (SetAttribute(cluster, proc, argv[nextarg],
							 argv[nextarg+1]) < 0) {
				fprintf(stderr,
						"Failed to set attribute \"%s\" for job %d.%d.\n",
						argv[nextarg], cluster, proc);
				exit(1);
			}
		}
		printf("Set attribute \"%s\".\n", argv[nextarg]);
	}

	if (!DisconnectQ(q)) {
		fprintf(stderr,
				"Queue transaction failed.  No attributes were set.\n");
		exit(1);
	}

	return 0;
}

#include "daemon_core_stubs.h"
<|endoftext|>


<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.20
Copyright (C) 2018  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "BoxDimensionsNonOrth.h"
#include "BoxDimensions.h"
#include "MoveConst.h" //For cutoff-related fail condition

void BoxDimensionsNonOrth::Init(config_setup::RestartSettings const& restart,
                                config_setup::Volume const& confVolume,
                                pdb_setup::Cryst1 const& cryst,
                                double rc, double rcSq)
{
  rCut = rc;
  rCutSq = rcSq;
  for (uint b = 0; b < BOX_TOTAL; b++) {
    if(restart.enable && cryst.hasVolume) {
      axis = cryst.axis;
      double alpha = cos(cryst.cellAngle[b][0] * M_PI / 180.0);
      double beta  = cos(cryst.cellAngle[b][1] * M_PI / 180.0);
      double gamma = cos(cryst.cellAngle[b][2] * M_PI / 180.0);
      if(float(cryst.cellAngle[b][0]) == 90.0)
        alpha = 0.0;
      if(float(cryst.cellAngle[b][1]) == 90.0)
        beta = 0.0;
      if(float(cryst.cellAngle[b][2]) == 90.0)
        gamma = 0.0;
      double cosASq = alpha * alpha;
      double cosBSq = beta * beta;
      double cosGSq = gamma * gamma;
      double temp = (alpha - beta * gamma) / (sqrt(1.0 - cosGSq));
      cellBasis[b].Set(0, 1.0, 0.0, 0.0);
      cellBasis[b].Set(1, gamma, sqrt(1.0 - cosGSq), 0.0);
      cellBasis[b].Set(2, beta, temp, sqrt(1.0 - cosBSq - temp * temp));
      cellBasis[b].Scale(0, axis.Get(b).x);
      cellBasis[b].Scale(1, axis.Get(b).y);
      cellBasis[b].Scale(2, axis.Get(b).z);
    } else if(confVolume.hasVolume) {
      confVolume.axis[b].CopyRange(cellBasis[b], 0, 0, 3);
    } else {
      fprintf(stderr,
              "Error: Cell Basis not specified in PDB or in.dat files.\n");
      exit(EXIT_FAILURE);
    }
    //Find the length of a, b, c
    cellLength.Set(b, cellBasis[b].Length(0), cellBasis[b].Length(1),
                   cellBasis[b].Length(2));
    //Find Cosine Angle of alpha, beta and gamma
    cosAngle[b][0] = Dot(cellBasis[b].Get(1), cellBasis[b].Get(2)) /
                     (cellLength.Get(b).y * cellLength.Get(b).z);
    cosAngle[b][1] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(2)) /
                     (cellLength.Get(b).x * cellLength.Get(b).z);
    cosAngle[b][2] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(1)) /
                     (cellLength.Get(b).x * cellLength.Get(b).y);
    //Calculate Cross Product
    XYZ axb = Cross(cellBasis[b].Get(0), cellBasis[b].Get(1));
    XYZ bxc = Cross(cellBasis[b].Get(1), cellBasis[b].Get(2));
    XYZ cxa = Cross(cellBasis[b].Get(2), cellBasis[b].Get(0));
    //Calculate volume = A.(B x C)
    volume[b] = abs(Dot(cellBasis[b].Get(0), bxc));
    volInv[b] = 1.0 / volume[b];
    //normalizing unitcell
    for(uint i = 0; i < 3; i++) {
      cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
    }
    //Calculate the adjoint and determinant
    double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
    //Calculate the inverse matrix of cell basis
    cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
    //Set the axis with unslant cell box
    //XYZ unslant = TransformUnSlant(cellLength.Get(b), b);
    //axis.Set(b, unslant.x, unslant.y, unslant.z);
    axis.Set(b, cellLength[b]);
  }
  //Set half axis
  axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);
  halfAx.ScaleRange(0, BOX_TOTAL, 0.5);

  for (uint b = 0; b < BOX_TOTAL; b++) {
    //check to see if initial box size is cubic or not
    cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));
    //check to see if box is orthogonal or not
    orthogonal[b] = ((cosAngle[b][0] == 0.0) &&
                     (cosAngle[b][1] == 0.0) &&
                     (cosAngle[b][2] == 0.0));
  }
  constArea = confVolume.cstArea;
}

void BoxDimensionsNonOrth::CalcCellDimensions(const uint b)
{
  //normalizing unitcell
  for(uint i = 0; i < 3; i++) {
    cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
  }
  //Calculate the adjoint and determinant
  double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
  //Calculate the inverse matrix of cell basis
  cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
}

BoxDimensionsNonOrth& BoxDimensionsNonOrth::operator=(BoxDimensionsNonOrth const& other)
{
  for (uint b = 0; b < BOX_TOTAL; ++b) {
    other.cellBasis[b].CopyRange(cellBasis[b], 0, 0, 3);
    other.cellBasis_Inv[b].CopyRange(cellBasis_Inv[b], 0, 0, 3);
    volume[b] = other.volume[b];
    volInv[b] = other.volInv[b];
    cubic[b] = other.cubic[b];
    orthogonal[b] = other.orthogonal[b];
    for(uint i = 0; i < 0; i++) {
      cosAngle[b][i] = other.cosAngle[b][i];
    }
  }
  other.axis.CopyRange(axis, 0, 0, BOX_TOTAL);
  other.halfAx.CopyRange(halfAx, 0, 0, BOX_TOTAL);
  other.cellLength.CopyRange(cellLength, 0, 0, BOX_TOTAL);
  rCut = other.rCut;
  rCutSq = other.rCutSq;
  constArea = other.constArea;
  return *this;
}

uint BoxDimensionsNonOrth::ShiftVolume(BoxDimensionsNonOrth & newDim,
                                       XYZ & scale, const uint b,
                                       const double delta) const
{
  uint rejectState = mv::fail_state::NO_FAIL;
  double newVolume = volume[b] + delta;
  newDim = *this;
  newDim.SetVolume(b, newVolume);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
       newDim.halfAx.z[b] < rCut)) {
    std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
              << std::endl;
    rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
  }
  scale = newDim.axis.Get(b) / axis.Get(b);

  return rejectState;
}

uint BoxDimensionsNonOrth::ExchangeVolume(BoxDimensionsNonOrth & newDim,
    XYZ * scale,
    const double transfer) const
{
  uint state = mv::fail_state::NO_FAIL;
  double vTot = GetTotVolume();
  newDim = *this;

  newDim.SetVolume(0, volume[0] + transfer);
  newDim.SetVolume(1, vTot - newDim.volume[0]);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++) {
    scale[b] = newDim.axis.Get(b) / axis.Get(b);
    if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
         newDim.halfAx.z[b] < rCut)) {
      std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
                << std::endl;
      state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
    }
  }
  return state;
}

void BoxDimensionsNonOrth::SetVolume(const uint b, const double vol)
{
  if(constArea) {
    double ratio = vol / volume[b];
    axis.Scale(b, 1.0, 1.0, ratio);
    halfAx.Scale(b, 1.0, 1.0, ratio);
    cellLength.Scale(b, 1.0, 1.0, ratio);
    //Keep a and b same and change c
    cellBasis[b].Scale(2, ratio);
  } else {
    double ratio = pow(vol / volume[b], (1.0 / 3.0));
    axis.Scale(b, ratio);
    halfAx.Scale(b, ratio);
    cellLength.Scale(b, ratio);
    for(uint i = 0; i < 0; i++) {
      cellBasis[b].Scale(i, ratio);
    }
  }
  volume[b] = vol;
  volInv[b] = 1.0 / volume[b];
  //Calculate new cell dimension
  CalcCellDimensions(b);
}

XYZ BoxDimensionsNonOrth::MinImage(XYZ rawVecRef, const uint b) const
{
  XYZ rawVec = TransformUnSlant(rawVecRef, b);
  rawVecRef = BoxDimensions:: MinImage(rawVec, b);
  rawVecRef = TransformSlant(rawVecRef, b);
  return rawVecRef;
}

void BoxDimensionsNonOrth::WrapPBC(double &x, double &y, double &z,
                                   const uint b) const
{
  //convert XYZ to unslant
  XYZ unwrap(x, y, z);
  XYZ unslant = TransformUnSlant(unwrap, b);
  BoxDimensions::WrapPBC(unslant.x, axis.x[b]);
  BoxDimensions::WrapPBC(unslant.y, axis.y[b]);
  BoxDimensions::WrapPBC(unslant.z, axis.z[b]);
  //convert XYZ to slant
  XYZ slant = TransformSlant(unslant, b);
  x = slant.x;
  y = slant.y;
  z = slant.z;
}

void BoxDimensionsNonOrth::UnwrapPBC(double & x, double & y, double & z,
                                     const uint b, XYZ const& ref) const
{
  //convert XYZ to unslant
  XYZ wrap(x, y, z);
  XYZ unslant = TransformUnSlant(wrap, b);
  XYZ unslantRef = TransformUnSlant(ref, b);
  BoxDimensions::UnwrapPBC(unslant.x, unslantRef.x, axis.x[b], halfAx.x[b]);
  BoxDimensions::UnwrapPBC(unslant.y, unslantRef.y, axis.y[b], halfAx.y[b]);
  BoxDimensions::UnwrapPBC(unslant.z, unslantRef.z, axis.z[b], halfAx.z[b]);
  XYZ unwrap(x, y, z);
  //convert XYZ to slant
  XYZ slant = TransformSlant(unslant, b);
  x = slant.x;
  y = slant.y;
  z = slant.z;
}<commit_msg>error fix<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.20
Copyright (C) 2018  GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "BoxDimensionsNonOrth.h"
#include "BoxDimensions.h"
#include "GeomLib.h"
#include "MoveConst.h" //For cutoff-related fail condition

using namespace geom;

void BoxDimensionsNonOrth::Init(config_setup::RestartSettings const& restart,
                                config_setup::Volume const& confVolume,
                                pdb_setup::Cryst1 const& cryst,
                                double rc, double rcSq)
{
  rCut = rc;
  rCutSq = rcSq;
  for (uint b = 0; b < BOX_TOTAL; b++) {
    if(restart.enable && cryst.hasVolume) {
      axis = cryst.axis;
      double alpha = cos(cryst.cellAngle[b][0] * M_PI / 180.0);
      double beta  = cos(cryst.cellAngle[b][1] * M_PI / 180.0);
      double gamma = cos(cryst.cellAngle[b][2] * M_PI / 180.0);
      if(float(cryst.cellAngle[b][0]) == 90.0)
        alpha = 0.0;
      if(float(cryst.cellAngle[b][1]) == 90.0)
        beta = 0.0;
      if(float(cryst.cellAngle[b][2]) == 90.0)
        gamma = 0.0;
      double cosASq = alpha * alpha;
      double cosBSq = beta * beta;
      double cosGSq = gamma * gamma;
      double temp = (alpha - beta * gamma) / (sqrt(1.0 - cosGSq));
      cellBasis[b].Set(0, 1.0, 0.0, 0.0);
      cellBasis[b].Set(1, gamma, sqrt(1.0 - cosGSq), 0.0);
      cellBasis[b].Set(2, beta, temp, sqrt(1.0 - cosBSq - temp * temp));
      cellBasis[b].Scale(0, axis.Get(b).x);
      cellBasis[b].Scale(1, axis.Get(b).y);
      cellBasis[b].Scale(2, axis.Get(b).z);
    } else if(confVolume.hasVolume) {
      confVolume.axis[b].CopyRange(cellBasis[b], 0, 0, 3);
    } else {
      fprintf(stderr,
              "Error: Cell Basis not specified in PDB or in.dat files.\n");
      exit(EXIT_FAILURE);
    }
    //Find the length of a, b, c
    cellLength.Set(b, cellBasis[b].Length(0), cellBasis[b].Length(1),
                   cellBasis[b].Length(2));
    //Find Cosine Angle of alpha, beta and gamma
    cosAngle[b][0] = Dot(cellBasis[b].Get(1), cellBasis[b].Get(2)) /
                     (cellLength.Get(b).y * cellLength.Get(b).z);
    cosAngle[b][1] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(2)) /
                     (cellLength.Get(b).x * cellLength.Get(b).z);
    cosAngle[b][2] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(1)) /
                     (cellLength.Get(b).x * cellLength.Get(b).y);
    //Calculate Cross Product
    XYZ axb = Cross(cellBasis[b].Get(0), cellBasis[b].Get(1));
    XYZ bxc = Cross(cellBasis[b].Get(1), cellBasis[b].Get(2));
    XYZ cxa = Cross(cellBasis[b].Get(2), cellBasis[b].Get(0));
    //Calculate volume = A.(B x C)
    volume[b] = abs(Dot(cellBasis[b].Get(0), bxc));
    volInv[b] = 1.0 / volume[b];
    //normalizing unitcell
    for(uint i = 0; i < 3; i++) {
      cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
    }
    //Calculate the adjoint and determinant
    double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
    //Calculate the inverse matrix of cell basis
    cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
    //Set the axis with unslant cell box
    //XYZ unslant = TransformUnSlant(cellLength.Get(b), b);
    //axis.Set(b, unslant.x, unslant.y, unslant.z);
    axis.Set(b, cellLength[b]);
  }
  //Set half axis
  axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);
  halfAx.ScaleRange(0, BOX_TOTAL, 0.5);

  for (uint b = 0; b < BOX_TOTAL; b++) {
    //check to see if initial box size is cubic or not
    cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));
    //check to see if box is orthogonal or not
    orthogonal[b] = ((cosAngle[b][0] == 0.0) &&
                     (cosAngle[b][1] == 0.0) &&
                     (cosAngle[b][2] == 0.0));
  }
  constArea = confVolume.cstArea;
}

void BoxDimensionsNonOrth::CalcCellDimensions(const uint b)
{
  //normalizing unitcell
  for(uint i = 0; i < 3; i++) {
    cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());
  }
  //Calculate the adjoint and determinant
  double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);
  //Calculate the inverse matrix of cell basis
  cellBasis_Inv[b].ScaleRange(0, 3, 1.0 / det);
}

BoxDimensionsNonOrth& BoxDimensionsNonOrth::operator=(BoxDimensionsNonOrth const& other)
{
  for (uint b = 0; b < BOX_TOTAL; ++b) {
    other.cellBasis[b].CopyRange(cellBasis[b], 0, 0, 3);
    other.cellBasis_Inv[b].CopyRange(cellBasis_Inv[b], 0, 0, 3);
    volume[b] = other.volume[b];
    volInv[b] = other.volInv[b];
    cubic[b] = other.cubic[b];
    orthogonal[b] = other.orthogonal[b];
    for(uint i = 0; i < 0; i++) {
      cosAngle[b][i] = other.cosAngle[b][i];
    }
  }
  other.axis.CopyRange(axis, 0, 0, BOX_TOTAL);
  other.halfAx.CopyRange(halfAx, 0, 0, BOX_TOTAL);
  other.cellLength.CopyRange(cellLength, 0, 0, BOX_TOTAL);
  rCut = other.rCut;
  rCutSq = other.rCutSq;
  constArea = other.constArea;
  return *this;
}

uint BoxDimensionsNonOrth::ShiftVolume(BoxDimensionsNonOrth & newDim,
                                       XYZ & scale, const uint b,
                                       const double delta) const
{
  uint rejectState = mv::fail_state::NO_FAIL;
  double newVolume = volume[b] + delta;
  newDim = *this;
  newDim.SetVolume(b, newVolume);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
       newDim.halfAx.z[b] < rCut)) {
    std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
              << std::endl;
    rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
  }
  scale = newDim.axis.Get(b) / axis.Get(b);

  return rejectState;
}

uint BoxDimensionsNonOrth::ExchangeVolume(BoxDimensionsNonOrth & newDim,
    XYZ * scale,
    const double transfer) const
{
  uint state = mv::fail_state::NO_FAIL;
  double vTot = GetTotVolume();
  newDim = *this;

  newDim.SetVolume(0, volume[0] + transfer);
  newDim.SetVolume(1, vTot - newDim.volume[0]);

  //If move would shrink any box axis to be less than 2 * rcut, then
  //automatically reject to prevent errors.
  for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++) {
    scale[b] = newDim.axis.Get(b) / axis.Get(b);
    if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||
         newDim.halfAx.z[b] < rCut)) {
      std::cout << "WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!"
                << std::endl;
      state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;
    }
  }
  return state;
}

void BoxDimensionsNonOrth::SetVolume(const uint b, const double vol)
{
  if(constArea) {
    double ratio = vol / volume[b];
    axis.Scale(b, 1.0, 1.0, ratio);
    halfAx.Scale(b, 1.0, 1.0, ratio);
    cellLength.Scale(b, 1.0, 1.0, ratio);
    //Keep a and b same and change c
    cellBasis[b].Scale(2, ratio);
  } else {
    double ratio = pow(vol / volume[b], (1.0 / 3.0));
    axis.Scale(b, ratio);
    halfAx.Scale(b, ratio);
    cellLength.Scale(b, ratio);
    for(uint i = 0; i < 0; i++) {
      cellBasis[b].Scale(i, ratio);
    }
  }
  volume[b] = vol;
  volInv[b] = 1.0 / volume[b];
  //Calculate new cell dimension
  CalcCellDimensions(b);
}

XYZ BoxDimensionsNonOrth::MinImage(XYZ rawVecRef, const uint b) const
{
  XYZ rawVec = TransformUnSlant(rawVecRef, b);
  rawVecRef = BoxDimensions:: MinImage(rawVec, b);
  rawVecRef = TransformSlant(rawVecRef, b);
  return rawVecRef;
}

void BoxDimensionsNonOrth::WrapPBC(double &x, double &y, double &z,
                                   const uint b) const
{
  //convert XYZ to unslant
  XYZ unwrap(x, y, z);
  XYZ unslant = TransformUnSlant(unwrap, b);
  BoxDimensions::WrapPBC(unslant.x, axis.x[b]);
  BoxDimensions::WrapPBC(unslant.y, axis.y[b]);
  BoxDimensions::WrapPBC(unslant.z, axis.z[b]);
  //convert XYZ to slant
  XYZ slant = TransformSlant(unslant, b);
  x = slant.x;
  y = slant.y;
  z = slant.z;
}

void BoxDimensionsNonOrth::UnwrapPBC(double & x, double & y, double & z,
                                     const uint b, XYZ const& ref) const
{
  //convert XYZ to unslant
  XYZ wrap(x, y, z);
  XYZ unslant = TransformUnSlant(wrap, b);
  XYZ unslantRef = TransformUnSlant(ref, b);
  BoxDimensions::UnwrapPBC(unslant.x, unslantRef.x, axis.x[b], halfAx.x[b]);
  BoxDimensions::UnwrapPBC(unslant.y, unslantRef.y, axis.y[b], halfAx.y[b]);
  BoxDimensions::UnwrapPBC(unslant.z, unslantRef.z, axis.z[b], halfAx.z[b]);
  XYZ unwrap(x, y, z);
  //convert XYZ to slant
  XYZ slant = TransformSlant(unslant, b);
  x = slant.x;
  y = slant.y;
  z = slant.z;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: editable.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: nn $ $Date: 2002-11-20 14:32:18 $
 *
 *  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 SC_EDITABLE_HXX
#define SC_EDITABLE_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class ScDocument;
class ScViewFunc;
class ScMarkData;
class ScRange;

class ScEditableTester
{
    BOOL    bIsEditable;
    BOOL    bOnlyMatrix;

public:
            // no test in ctor
            ScEditableTester();

            // calls TestBlock
            ScEditableTester( ScDocument* pDoc, USHORT nTab,
                        USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow );

            // calls TestSelectedBlock
            ScEditableTester( ScDocument* pDoc,
                        USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow,
                        const ScMarkData& rMark );

            // calls TestRange
            ScEditableTester( ScDocument* pDoc, const ScRange& rRange );

            // calls TestSelection
            ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );

            // calls TestView
            ScEditableTester( ScViewFunc* pView );

            ~ScEditableTester() {}

            // Several calls to the Test... methods check if *all* of the ranges
            // are editable. For several independent checks, Reset() has to be used.
    void    TestBlock( ScDocument* pDoc, USHORT nTab,
                        USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow );
    void    TestSelectedBlock( ScDocument* pDoc,
                        USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow,
                        const ScMarkData& rMark );
    void    TestRange( ScDocument* pDoc, const ScRange& rRange );
    void    TestSelection( ScDocument* pDoc, const ScMarkData& rMark );
    void    TestView( ScViewFunc* pView );

    void    Reset();

    BOOL    IsEditable() const          { return bIsEditable; }
    BOOL    IsFormatEditable() const    { return bIsEditable || bOnlyMatrix; }
    USHORT  GetMessageId() const;
};

#endif

<commit_msg>INTEGRATION: CWS rowlimit (1.1.302); FILE MERGED 2004/01/13 20:04:15 er 1.1.302.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
 *
 *  $RCSfile: editable.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:33:11 $
 *
 *  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 SC_EDITABLE_HXX
#define SC_EDITABLE_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class ScDocument;
class ScViewFunc;
class ScMarkData;
class ScRange;

class ScEditableTester
{
    BOOL    bIsEditable;
    BOOL    bOnlyMatrix;

public:
            // no test in ctor
            ScEditableTester();

            // calls TestBlock
            ScEditableTester( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );

            // calls TestSelectedBlock
            ScEditableTester( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark );

            // calls TestRange
            ScEditableTester( ScDocument* pDoc, const ScRange& rRange );

            // calls TestSelection
            ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );

            // calls TestView
            ScEditableTester( ScViewFunc* pView );

            ~ScEditableTester() {}

            // Several calls to the Test... methods check if *all* of the ranges
            // are editable. For several independent checks, Reset() has to be used.
    void    TestBlock( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );
    void    TestSelectedBlock( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark );
    void    TestRange( ScDocument* pDoc, const ScRange& rRange );
    void    TestSelection( ScDocument* pDoc, const ScMarkData& rMark );
    void    TestView( ScViewFunc* pView );

    void    Reset();

    BOOL    IsEditable() const          { return bIsEditable; }
    BOOL    IsFormatEditable() const    { return bIsEditable || bOnlyMatrix; }
    USHORT  GetMessageId() const;
};

#endif

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libetonyek project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <stdio.h>
#include <string.h>

#include <libwpd-stream/libwpd-stream.h>
#include <libwpd/libwpd.h>
#include <libetonyek/libetonyek.h>

#include "KEYDirectoryStream.h"

class TextPainter : public libetonyek::KEYPresentationInterface
{
public:
  TextPainter();

  virtual void startDocument(const ::WPXPropertyList &propList);
  virtual void endDocument();
  virtual void setDocumentMetaData(const ::WPXPropertyList &propList);
  virtual void startSlide(const ::WPXPropertyList &propList);
  virtual void endSlide();
  virtual void startLayer(const ::WPXPropertyList &propList);
  virtual void endLayer();
  virtual void startEmbeddedGraphics(const ::WPXPropertyList &propList);
  virtual void endEmbeddedGraphics();
  virtual void startGroup(const ::WPXPropertyList &propList);
  virtual void endGroup();

  virtual void setStyle(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &gradient);

  virtual void drawRectangle(const ::WPXPropertyList &propList);
  virtual void drawEllipse(const ::WPXPropertyList &propList);
  virtual void drawPolyline(const ::WPXPropertyListVector &vertices);
  virtual void drawPolygon(const ::WPXPropertyListVector &vertices);
  virtual void drawPath(const ::WPXPropertyListVector &path);
  virtual void drawGraphicObject(const ::WPXPropertyList &propList, const ::WPXBinaryData &binaryData);
  virtual void drawConnector(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);

  virtual void startTextObject(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);
  virtual void endTextObject();
  virtual void openParagraph(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
  virtual void closeParagraph();
  virtual void openSpan(const ::WPXPropertyList &propList);
  virtual void closeSpan();
  virtual void insertTab();
  virtual void insertSpace();
  virtual void insertText(const ::WPXString &str);
  virtual void insertLineBreak();

  virtual void insertField(const WPXString &type, const ::WPXPropertyList &propList);

  virtual void openOrderedListLevel(const ::WPXPropertyList &propList);
  virtual void openUnorderedListLevel(const ::WPXPropertyList &propList);
  virtual void closeOrderedListLevel();
  virtual void closeUnorderedListLevel();
  virtual void openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
  virtual void closeListElement();

  virtual void openTable(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &columns);
  virtual void openTableRow(const ::WPXPropertyList &propList);
  virtual void closeTableRow();
  virtual void openTableCell(const ::WPXPropertyList &propList);
  virtual void closeTableCell();
  virtual void insertCoveredTableCell(const ::WPXPropertyList &propList);
  virtual void closeTable();

  virtual void startComment(const ::WPXPropertyList &propList);
  virtual void endComment();

  virtual void startNotes(const ::WPXPropertyList &propList);
  virtual void endNotes();
};

TextPainter::TextPainter()
{
}

void TextPainter::startDocument(const ::WPXPropertyList &)
{
}

void TextPainter::endDocument()
{
}

void TextPainter::setDocumentMetaData(const ::WPXPropertyList &)
{
}

void TextPainter::startSlide(const ::WPXPropertyList &)
{
}

void TextPainter::endSlide()
{
  printf("\n");
}

void TextPainter::startLayer(const ::WPXPropertyList &)
{
}

void TextPainter::endLayer()
{
}

void TextPainter::startEmbeddedGraphics(const ::WPXPropertyList &)
{
}

void TextPainter::endEmbeddedGraphics()
{
}

void TextPainter::startGroup(const ::WPXPropertyList &)
{
}

void TextPainter::endGroup()
{
}

void TextPainter::setStyle(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::drawRectangle(const ::WPXPropertyList &)
{
}

void TextPainter::drawEllipse(const ::WPXPropertyList &)
{
}

void TextPainter::drawPolyline(const ::WPXPropertyListVector &)
{
}

void TextPainter::drawPolygon(const ::WPXPropertyListVector &)
{
}

void TextPainter::drawPath(const ::WPXPropertyListVector &)
{
}

void TextPainter::drawGraphicObject(const ::WPXPropertyList &, const ::WPXBinaryData &)
{
}

void TextPainter::drawConnector(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::startTextObject(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::endTextObject()
{
  printf("\n");
}

void TextPainter::openParagraph(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::closeParagraph()
{
  printf("\n");
}

void TextPainter::openSpan(const ::WPXPropertyList &)
{
}

void TextPainter::closeSpan()
{
}

void TextPainter::insertText(const ::WPXString &str)
{
  printf(str.cstr());
}

void TextPainter::insertTab()
{
  printf("\t");
}

void TextPainter::insertSpace()
{
  printf(" ");
}

void TextPainter::insertLineBreak()
{
  printf("\n");
}

void TextPainter::insertField(const WPXString &, const ::WPXPropertyList &)
{
}

void TextPainter::openOrderedListLevel(const ::WPXPropertyList &)
{
}

void TextPainter::openUnorderedListLevel(const ::WPXPropertyList &)
{
}

void TextPainter::closeOrderedListLevel()
{
}

void TextPainter::closeUnorderedListLevel()
{
}

void TextPainter::openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops)
{
  openParagraph(propList, tabStops);
}

void TextPainter::closeListElement()
{
  closeParagraph();
}

void TextPainter::openTable(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::openTableRow(const ::WPXPropertyList &)
{
}

void TextPainter::closeTableRow()
{
}

void TextPainter::openTableCell(const ::WPXPropertyList &)
{
}

void TextPainter::closeTableCell()
{
}

void TextPainter::insertCoveredTableCell(const ::WPXPropertyList &)
{
}

void TextPainter::closeTable()
{
}

void TextPainter::startComment(const ::WPXPropertyList &)
{
}

void TextPainter::endComment()
{
}

void TextPainter::startNotes(const ::WPXPropertyList &)
{
}

void TextPainter::endNotes()
{
}

namespace
{

int printUsage()
{
  printf("Usage: key2text [OPTION] <KeyNote Document> | <KeyNote Directory>\n");
  printf("\n");
  printf("Options:\n");
  printf("--help                Shows this help message\n");
  return -1;
}

} // anonymous namespace

int main(int argc, char *argv[])
{
  if (argc < 2)
    return printUsage();

  char *file = 0;

  for (int i = 1; i < argc; i++)
  {
    if (!file && strncmp(argv[i], "--", 2))
      file = argv[i];
    else
      return printUsage();
  }

  if (!file)
    return printUsage();

  using boost::shared_ptr;
  namespace fs = boost::filesystem;

  fs::path path(file);
  shared_ptr<WPXInputStream> input;
  if (is_directory(path))
    input.reset(new conv::KEYDirectoryStream(path));
  else
    input.reset(new WPXFileStream(file));

  libetonyek::KEYDocumentType type = libetonyek::KEY_DOCUMENT_TYPE_UNKNOWN;
  if (!libetonyek::KEYDocument::isSupported(input.get(), &type))
  {
    fprintf(stderr, "ERROR: Unsupported file format!\n");
    return 1;
  }

  if (libetonyek::KEY_DOCUMENT_TYPE_APXL_FILE == type)
  {
    path.remove_filename();
    input.reset(new conv::KEYDirectoryStream(path));
  }

  TextPainter painter;
  libetonyek::KEYDocument::parse(input.get(), &painter);

  return 0;
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>WaE: format string is not a string literal<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * This file is part of the libetonyek project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <stdio.h>
#include <string.h>

#include <libwpd-stream/libwpd-stream.h>
#include <libwpd/libwpd.h>
#include <libetonyek/libetonyek.h>

#include "KEYDirectoryStream.h"

class TextPainter : public libetonyek::KEYPresentationInterface
{
public:
  TextPainter();

  virtual void startDocument(const ::WPXPropertyList &propList);
  virtual void endDocument();
  virtual void setDocumentMetaData(const ::WPXPropertyList &propList);
  virtual void startSlide(const ::WPXPropertyList &propList);
  virtual void endSlide();
  virtual void startLayer(const ::WPXPropertyList &propList);
  virtual void endLayer();
  virtual void startEmbeddedGraphics(const ::WPXPropertyList &propList);
  virtual void endEmbeddedGraphics();
  virtual void startGroup(const ::WPXPropertyList &propList);
  virtual void endGroup();

  virtual void setStyle(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &gradient);

  virtual void drawRectangle(const ::WPXPropertyList &propList);
  virtual void drawEllipse(const ::WPXPropertyList &propList);
  virtual void drawPolyline(const ::WPXPropertyListVector &vertices);
  virtual void drawPolygon(const ::WPXPropertyListVector &vertices);
  virtual void drawPath(const ::WPXPropertyListVector &path);
  virtual void drawGraphicObject(const ::WPXPropertyList &propList, const ::WPXBinaryData &binaryData);
  virtual void drawConnector(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);

  virtual void startTextObject(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);
  virtual void endTextObject();
  virtual void openParagraph(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
  virtual void closeParagraph();
  virtual void openSpan(const ::WPXPropertyList &propList);
  virtual void closeSpan();
  virtual void insertTab();
  virtual void insertSpace();
  virtual void insertText(const ::WPXString &str);
  virtual void insertLineBreak();

  virtual void insertField(const WPXString &type, const ::WPXPropertyList &propList);

  virtual void openOrderedListLevel(const ::WPXPropertyList &propList);
  virtual void openUnorderedListLevel(const ::WPXPropertyList &propList);
  virtual void closeOrderedListLevel();
  virtual void closeUnorderedListLevel();
  virtual void openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);
  virtual void closeListElement();

  virtual void openTable(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &columns);
  virtual void openTableRow(const ::WPXPropertyList &propList);
  virtual void closeTableRow();
  virtual void openTableCell(const ::WPXPropertyList &propList);
  virtual void closeTableCell();
  virtual void insertCoveredTableCell(const ::WPXPropertyList &propList);
  virtual void closeTable();

  virtual void startComment(const ::WPXPropertyList &propList);
  virtual void endComment();

  virtual void startNotes(const ::WPXPropertyList &propList);
  virtual void endNotes();
};

TextPainter::TextPainter()
{
}

void TextPainter::startDocument(const ::WPXPropertyList &)
{
}

void TextPainter::endDocument()
{
}

void TextPainter::setDocumentMetaData(const ::WPXPropertyList &)
{
}

void TextPainter::startSlide(const ::WPXPropertyList &)
{
}

void TextPainter::endSlide()
{
  printf("\n");
}

void TextPainter::startLayer(const ::WPXPropertyList &)
{
}

void TextPainter::endLayer()
{
}

void TextPainter::startEmbeddedGraphics(const ::WPXPropertyList &)
{
}

void TextPainter::endEmbeddedGraphics()
{
}

void TextPainter::startGroup(const ::WPXPropertyList &)
{
}

void TextPainter::endGroup()
{
}

void TextPainter::setStyle(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::drawRectangle(const ::WPXPropertyList &)
{
}

void TextPainter::drawEllipse(const ::WPXPropertyList &)
{
}

void TextPainter::drawPolyline(const ::WPXPropertyListVector &)
{
}

void TextPainter::drawPolygon(const ::WPXPropertyListVector &)
{
}

void TextPainter::drawPath(const ::WPXPropertyListVector &)
{
}

void TextPainter::drawGraphicObject(const ::WPXPropertyList &, const ::WPXBinaryData &)
{
}

void TextPainter::drawConnector(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::startTextObject(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::endTextObject()
{
  printf("\n");
}

void TextPainter::openParagraph(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::closeParagraph()
{
  printf("\n");
}

void TextPainter::openSpan(const ::WPXPropertyList &)
{
}

void TextPainter::closeSpan()
{
}

void TextPainter::insertText(const ::WPXString &str)
{
  printf("%s", str.cstr());
}

void TextPainter::insertTab()
{
  printf("\t");
}

void TextPainter::insertSpace()
{
  printf(" ");
}

void TextPainter::insertLineBreak()
{
  printf("\n");
}

void TextPainter::insertField(const WPXString &, const ::WPXPropertyList &)
{
}

void TextPainter::openOrderedListLevel(const ::WPXPropertyList &)
{
}

void TextPainter::openUnorderedListLevel(const ::WPXPropertyList &)
{
}

void TextPainter::closeOrderedListLevel()
{
}

void TextPainter::closeUnorderedListLevel()
{
}

void TextPainter::openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops)
{
  openParagraph(propList, tabStops);
}

void TextPainter::closeListElement()
{
  closeParagraph();
}

void TextPainter::openTable(const ::WPXPropertyList &, const ::WPXPropertyListVector &)
{
}

void TextPainter::openTableRow(const ::WPXPropertyList &)
{
}

void TextPainter::closeTableRow()
{
}

void TextPainter::openTableCell(const ::WPXPropertyList &)
{
}

void TextPainter::closeTableCell()
{
}

void TextPainter::insertCoveredTableCell(const ::WPXPropertyList &)
{
}

void TextPainter::closeTable()
{
}

void TextPainter::startComment(const ::WPXPropertyList &)
{
}

void TextPainter::endComment()
{
}

void TextPainter::startNotes(const ::WPXPropertyList &)
{
}

void TextPainter::endNotes()
{
}

namespace
{

int printUsage()
{
  printf("Usage: key2text [OPTION] <KeyNote Document> | <KeyNote Directory>\n");
  printf("\n");
  printf("Options:\n");
  printf("--help                Shows this help message\n");
  return -1;
}

} // anonymous namespace

int main(int argc, char *argv[])
{
  if (argc < 2)
    return printUsage();

  char *file = 0;

  for (int i = 1; i < argc; i++)
  {
    if (!file && strncmp(argv[i], "--", 2))
      file = argv[i];
    else
      return printUsage();
  }

  if (!file)
    return printUsage();

  using boost::shared_ptr;
  namespace fs = boost::filesystem;

  fs::path path(file);
  shared_ptr<WPXInputStream> input;
  if (is_directory(path))
    input.reset(new conv::KEYDirectoryStream(path));
  else
    input.reset(new WPXFileStream(file));

  libetonyek::KEYDocumentType type = libetonyek::KEY_DOCUMENT_TYPE_UNKNOWN;
  if (!libetonyek::KEYDocument::isSupported(input.get(), &type))
  {
    fprintf(stderr, "ERROR: Unsupported file format!\n");
    return 1;
  }

  if (libetonyek::KEY_DOCUMENT_TYPE_APXL_FILE == type)
  {
    path.remove_filename();
    input.reset(new conv::KEYDirectoryStream(path));
  }

  TextPainter painter;
  libetonyek::KEYDocument::parse(input.get(), &painter);

  return 0;
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>


<commit_before>#include "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "context/static_context.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "compiler/rewriter/framework/rule_driver.h"

#include <memory>

using namespace std;

namespace zorba {

  class SubstVars : public RewriteRule {
  protected:
    var_expr *var;
    expr *subst;

  public:
    SubstVars (var_expr *var_, expr *subst_) : var (var_), subst (subst_) {}
    expr_t rewritePre(expr *node, RewriterContext& rCtx);
    expr_t rewritePost(expr *node, RewriterContext& rCtx);
  };

  RULE_REWRITE_PRE(SubstVars) {
    return (node == var) ? subst : NULL;
  }
  RULE_REWRITE_POST(SubstVars) {
    return NULL;
  }

  expr_t subst_vars (RewriterContext& rCtx, var_expr *var, expr *subst) {
    auto_ptr<Rewriter> rw (new SingletonRuleMajorDriverBase (RuleMajorDriver::rule_ptr_t (new SubstVars (var, subst))));
    rw->rewrite (rCtx);
    return rCtx.getRoot ();
  }

RULE_REWRITE_PRE(EliminateUnusedLetVars)
{
  static_context *sctx = rCtx.getStaticContext();
  TypeManager *ts = sctx->get_typemanager();
  flwor_expr *flwor = dynamic_cast<flwor_expr *>(node);
  if (flwor != NULL) {
    flwor_expr::clause_list_t::iterator i = flwor->clause_begin();
    while(i != flwor->clause_end()) {
      flwor_expr::forletref_t ref = *i;
      expr *cexpr = ref->get_expr ();
      forlet_clause::varref_t vref = ref->get_var();
      bool is_let = vref->get_kind() == var_expr::let_var;
      int quant_cnt = 2;  // cardinality of for clause: 0, 1 or more
      if (! is_let) {
        xqtref_t ctype = cexpr->return_type (sctx);
        if (ts->is_equal (*ctype, *ts->create_empty_type ()))
          quant_cnt = 0;
        else if (ts->quantifier (*ctype) == TypeConstants::QUANT_ONE)
          quant_cnt = 1;
      }
      if (is_let || quant_cnt < 2) {
        if (quant_cnt == 0) return new fo_expr (node->get_loc (), LOOKUP_OPN ("concatenate"));
        // otherwise is_let || quant_cnt == 1
        forlet_clause::varref_t pvref = ref->get_pos_var ();
        if (pvref != NULL)
          subst_vars (rCtx, pvref.getp (), new const_expr (node->get_loc (), xqp_integer::parseInt (1)));
        int uses = count_variable_uses(flwor, &*vref);
        if (uses > 1)
          ++i;
        else {
          if (uses == 1) {
            if (flwor->forlet_count () == 1 // TODO: if cardinality FLWOR result = 1...
                || cexpr->get_annotation (AnnotationKey::UNFOLDABLE_OP) != TSVAnnotationValue::TRUE_VALUE)
            {

              i = flwor->remove_forlet_clause (i);
              subst_vars (rCtx, vref, cexpr);
            }
            else ++i;
          } else {
            i = flwor->remove_forlet_clause(i);
          }
        }
      } else {
        ++i;
      }
    }
    if (flwor->forlet_count() == 0) {
      expr_t where = flwor->get_where();
      expr_t result = flwor->get_retval();
      if (where != NULL) {
        rchandle<if_expr> ite(new if_expr(where->get_loc()));
        ite->set_cond_expr(where);
        ite->set_then_expr(result);
        ite->set_else_expr(new fo_expr(where->get_loc(), LOOKUP_FN("fn", "concatenate", 0)));
        result = &*ite;
      }
      return result;
    }
  }
  return NULL;
}

RULE_REWRITE_POST(EliminateUnusedLetVars)
{
  return NULL;
}

}
/* vim:set ts=2 sw=2: */
<commit_msg>FLWOR rewrite: substitute consts<commit_after>#include "compiler/rewriter/rules/ruleset.h"
#include "compiler/expression/expr.h"
#include "context/static_context.h"
#include "compiler/rewriter/tools/expr_tools.h"
#include "compiler/rewriter/framework/rule_driver.h"

#include <memory>

using namespace std;

namespace zorba {

  class SubstVars : public RewriteRule {
  protected:
    var_expr *var;
    expr *subst;

  public:
    SubstVars (var_expr *var_, expr *subst_) : var (var_), subst (subst_) {}
    expr_t rewritePre(expr *node, RewriterContext& rCtx);
    expr_t rewritePost(expr *node, RewriterContext& rCtx);
  };

  RULE_REWRITE_PRE(SubstVars) {
    return (node == var) ? subst : NULL;
  }
  RULE_REWRITE_POST(SubstVars) {
    return NULL;
  }

  expr_t subst_vars (RewriterContext& rCtx, var_expr *var, expr *subst) {
    auto_ptr<Rewriter> rw (new SingletonRuleMajorDriverBase (RuleMajorDriver::rule_ptr_t (new SubstVars (var, subst))));
    rw->rewrite (rCtx);
    return rCtx.getRoot ();
  }

RULE_REWRITE_PRE(EliminateUnusedLetVars)
{
  static_context *sctx = rCtx.getStaticContext();
  TypeManager *ts = sctx->get_typemanager();
  flwor_expr *flwor = dynamic_cast<flwor_expr *>(node);
  if (flwor != NULL) {
    flwor_expr::clause_list_t::iterator i = flwor->clause_begin();
    while(i != flwor->clause_end()) {
      flwor_expr::forletref_t ref = *i;
      expr *cexpr = ref->get_expr ();
      forlet_clause::varref_t vref = ref->get_var();
      bool is_let = vref->get_kind() == var_expr::let_var;
      int quant_cnt = 2;  // cardinality of for clause: 0, 1 or more
      if (! is_let) {
        xqtref_t ctype = cexpr->return_type (sctx);
        if (ts->is_equal (*ctype, *ts->create_empty_type ()))
          quant_cnt = 0;
        else if (ts->quantifier (*ctype) == TypeConstants::QUANT_ONE)
          quant_cnt = 1;
      }
      if (is_let || quant_cnt < 2) {
        if (quant_cnt == 0) return new fo_expr (node->get_loc (), LOOKUP_OPN ("concatenate"));
        // otherwise is_let || quant_cnt == 1
        forlet_clause::varref_t pvref = ref->get_pos_var ();
        if (pvref != NULL)
          subst_vars (rCtx, pvref.getp (), new const_expr (node->get_loc (), xqp_integer::parseInt (1)));
        int uses = count_variable_uses(flwor, &*vref);
        if (uses > 1) {
          if (cexpr->get_expr_kind () == const_expr_kind) {
              i = flwor->remove_forlet_clause (i);
              subst_vars (rCtx, vref, cexpr);
          } else ++i;
        } else {
          if (uses == 1) {
            if (flwor->forlet_count () == 1 // TODO: if cardinality FLWOR result = 1...
                || cexpr->get_annotation (AnnotationKey::UNFOLDABLE_OP) != TSVAnnotationValue::TRUE_VALUE)
            {

              i = flwor->remove_forlet_clause (i);
              subst_vars (rCtx, vref, cexpr);
            }
            else ++i;
          } else {
            i = flwor->remove_forlet_clause(i);
          }
        }
      } else {
        ++i;
      }
    }
    if (flwor->forlet_count() == 0) {
      expr_t where = flwor->get_where();
      expr_t result = flwor->get_retval();
      if (where != NULL) {
        rchandle<if_expr> ite(new if_expr(where->get_loc()));
        ite->set_cond_expr(where);
        ite->set_then_expr(result);
        ite->set_else_expr(new fo_expr(where->get_loc(), LOOKUP_FN("fn", "concatenate", 0)));
        result = &*ite;
      }
      return result;
    }
  }
  return NULL;
}

RULE_REWRITE_POST(EliminateUnusedLetVars)
{
  return NULL;
}

}
/* vim:set ts=2 sw=2: */
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "vbastyle.hxx"
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>

using namespace ::ooo::vba;
using namespace ::com::sun::star;

static rtl::OUString DISPLAYNAME( RTL_CONSTASCII_USTRINGPARAM("DisplayName") );

uno::Reference< container::XNameAccess >
ScVbaStyle::getStylesNameContainer( const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException )
{
    uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( xModel, uno::UNO_QUERY_THROW);
    uno::Reference< container::XNameAccess > xStylesAccess( xStyleSupplier->getStyleFamilies()->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CellStyles" ) ) ), uno::UNO_QUERY_THROW );
    return xStylesAccess;
}

uno::Reference< beans::XPropertySet >
lcl_getStyleProps( const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& xModel ) throw ( script::BasicErrorException, uno::RuntimeException )
{

    uno::Reference< beans::XPropertySet > xStyleProps( ScVbaStyle::getStylesNameContainer( xModel )->getByName( sStyleName ), uno::UNO_QUERY_THROW );
    return xStyleProps;
}

void ScVbaStyle::initialise() throw ( uno::RuntimeException )
{
    if (!mxModel.is() )
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XModel Interface could not be retrieved")) );
    uno::Reference< lang::XServiceInfo > xServiceInfo( mxPropertySet, uno::UNO_QUERY_THROW );
    if ( !xServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.style.CellStyle" ) ) ) )
    {
            DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
    }
    mxStyle.set( mxPropertySet, uno::UNO_QUERY_THROW );

    uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( mxModel, uno::UNO_QUERY_THROW );
    mxStyleFamilyNameContainer.set(  ScVbaStyle::getStylesNameContainer( mxModel ), uno::UNO_QUERY_THROW );

}

ScVbaStyle::ScVbaStyle( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) :  ScVbaStyle_BASE( xParent, xContext, lcl_getStyleProps( sStyleName, _xModel ), _xModel, false ), mxModel( _xModel )
{
    try
    {
        initialise();
    }
    catch (uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
    }
}

ScVbaStyle::ScVbaStyle( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& _xPropertySet, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, _xPropertySet, _xModel, false ),  mxModel( _xModel )
{
    try
    {
        initialise();
    }
    catch (uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
    }
}

::sal_Bool SAL_CALL
ScVbaStyle::BuiltIn() throw (script::BasicErrorException, uno::RuntimeException)
{
    return !mxStyle->isUserDefined();

}
void SAL_CALL
ScVbaStyle::setName( const ::rtl::OUString& Name ) throw (script::BasicErrorException, uno::RuntimeException)
{
    mxStyle->setName(Name);
}

::rtl::OUString SAL_CALL
ScVbaStyle::getName() throw (script::BasicErrorException, uno::RuntimeException)
{
    return mxStyle->getName();
}

void SAL_CALL
ScVbaStyle::setNameLocal( const ::rtl::OUString& NameLocal ) throw (script::BasicErrorException, uno::RuntimeException)
{
    try
    {
        mxPropertySet->setPropertyValue(DISPLAYNAME, uno::makeAny( NameLocal ) );
    }
    catch (uno::Exception& e)
    {
        DebugHelper::exception(e);
    }
}

::rtl::OUString SAL_CALL
ScVbaStyle::getNameLocal() throw (script::BasicErrorException, uno::RuntimeException)
{
    rtl::OUString sName;
    try
    {
        mxPropertySet->getPropertyValue(DISPLAYNAME) >>= sName;
    }
    catch (uno::Exception &e)
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
    }
    return sName;
}

void SAL_CALL
ScVbaStyle::Delete() throw (script::BasicErrorException, uno::RuntimeException)
{
    try
    {
        mxStyleFamilyNameContainer->removeByName(mxStyle->getName());
    }
    catch (uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
    }
}

void SAL_CALL
ScVbaStyle::setMergeCells( const uno::Any& /*MergeCells*/ ) throw (script::BasicErrorException, uno::RuntimeException)
{
    DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
}

uno::Any SAL_CALL
ScVbaStyle::getMergeCells(  ) throw (script::BasicErrorException, uno::RuntimeException)
{
    DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
    return uno::Any();
}

rtl::OUString&
ScVbaStyle::getServiceImplName()
{
        static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaStyle") );
        return sImplName;
}

uno::Sequence< rtl::OUString >
ScVbaStyle::getServiceNames()
{
        static uno::Sequence< rtl::OUString > aServiceNames;
        if ( aServiceNames.getLength() == 0 )
        {
                aServiceNames.realloc( 1 );
                aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.excel.XStyle" ) );
        }
        return aServiceNames;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: unused variables<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "vbastyle.hxx"
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>

using namespace ::ooo::vba;
using namespace ::com::sun::star;

static rtl::OUString DISPLAYNAME( RTL_CONSTASCII_USTRINGPARAM("DisplayName") );

uno::Reference< container::XNameAccess >
ScVbaStyle::getStylesNameContainer( const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException )
{
    uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( xModel, uno::UNO_QUERY_THROW);
    uno::Reference< container::XNameAccess > xStylesAccess( xStyleSupplier->getStyleFamilies()->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "CellStyles" ) ) ), uno::UNO_QUERY_THROW );
    return xStylesAccess;
}

uno::Reference< beans::XPropertySet >
lcl_getStyleProps( const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& xModel ) throw ( script::BasicErrorException, uno::RuntimeException )
{

    uno::Reference< beans::XPropertySet > xStyleProps( ScVbaStyle::getStylesNameContainer( xModel )->getByName( sStyleName ), uno::UNO_QUERY_THROW );
    return xStyleProps;
}

void ScVbaStyle::initialise() throw ( uno::RuntimeException )
{
    if (!mxModel.is() )
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "XModel Interface could not be retrieved")) );
    uno::Reference< lang::XServiceInfo > xServiceInfo( mxPropertySet, uno::UNO_QUERY_THROW );
    if ( !xServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.style.CellStyle" ) ) ) )
    {
            DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
    }
    mxStyle.set( mxPropertySet, uno::UNO_QUERY_THROW );

    uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( mxModel, uno::UNO_QUERY_THROW );
    mxStyleFamilyNameContainer.set(  ScVbaStyle::getStylesNameContainer( mxModel ), uno::UNO_QUERY_THROW );

}

ScVbaStyle::ScVbaStyle( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) :  ScVbaStyle_BASE( xParent, xContext, lcl_getStyleProps( sStyleName, _xModel ), _xModel, false ), mxModel( _xModel )
{
    try
    {
        initialise();
    }
    catch (const uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
    }
}

ScVbaStyle::ScVbaStyle( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& _xPropertySet, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, _xPropertySet, _xModel, false ),  mxModel( _xModel )
{
    try
    {
        initialise();
    }
    catch (const uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
    }
}

::sal_Bool SAL_CALL
ScVbaStyle::BuiltIn() throw (script::BasicErrorException, uno::RuntimeException)
{
    return !mxStyle->isUserDefined();

}
void SAL_CALL
ScVbaStyle::setName( const ::rtl::OUString& Name ) throw (script::BasicErrorException, uno::RuntimeException)
{
    mxStyle->setName(Name);
}

::rtl::OUString SAL_CALL
ScVbaStyle::getName() throw (script::BasicErrorException, uno::RuntimeException)
{
    return mxStyle->getName();
}

void SAL_CALL
ScVbaStyle::setNameLocal( const ::rtl::OUString& NameLocal ) throw (script::BasicErrorException, uno::RuntimeException)
{
    try
    {
        mxPropertySet->setPropertyValue(DISPLAYNAME, uno::makeAny( NameLocal ) );
    }
    catch (const uno::Exception& e)
    {
        DebugHelper::exception(e);
    }
}

::rtl::OUString SAL_CALL
ScVbaStyle::getNameLocal() throw (script::BasicErrorException, uno::RuntimeException)
{
    rtl::OUString sName;
    try
    {
        mxPropertySet->getPropertyValue(DISPLAYNAME) >>= sName;
    }
    catch (const uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );
    }
    return sName;
}

void SAL_CALL
ScVbaStyle::Delete() throw (script::BasicErrorException, uno::RuntimeException)
{
    try
    {
        mxStyleFamilyNameContainer->removeByName(mxStyle->getName());
    }
    catch (const uno::Exception& )
    {
        DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());
    }
}

void SAL_CALL
ScVbaStyle::setMergeCells( const uno::Any& /*MergeCells*/ ) throw (script::BasicErrorException, uno::RuntimeException)
{
    DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
}

uno::Any SAL_CALL
ScVbaStyle::getMergeCells(  ) throw (script::BasicErrorException, uno::RuntimeException)
{
    DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());
    return uno::Any();
}

rtl::OUString&
ScVbaStyle::getServiceImplName()
{
        static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaStyle") );
        return sImplName;
}

uno::Sequence< rtl::OUString >
ScVbaStyle::getServiceNames()
{
        static uno::Sequence< rtl::OUString > aServiceNames;
        if ( aServiceNames.getLength() == 0 )
        {
                aServiceNames.realloc( 1 );
                aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.excel.XStyle" ) );
        }
        return aServiceNames;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>