Example #1
0
    template <class InputIterator>
    path& append(InputIterator begin, InputIterator end, const codecvt_type& cvt);

    //  -----  modifiers  -----

    void   clear() BOOST_NOEXCEPT             { m_pathname.clear(); }
    path&  make_preferred()
#   ifdef BOOST_POSIX_API
      { return *this; }  // POSIX no effect
#   else // BOOST_WINDOWS_API
      ;  // change slashes to backslashes
#   endif
    path&  remove_filename();
    path&  remove_trailing_separator();
    path&  replace_extension(const path& new_extension = path());
    void   swap(path& rhs) BOOST_NOEXCEPT     { m_pathname.swap(rhs.m_pathname); }

    //  -----  observers  -----
  
    //  For operating systems that format file paths differently than directory
    //  paths, return values from observers are formatted as file names unless there
    //  is a trailing separator, in which case returns are formatted as directory
    //  paths. POSIX and Windows make no such distinction.

    //  Implementations are permitted to return const values or const references.

    //  The string or path returned by an observer are specified as being formatted
    //  as "native" or "generic".
    //
    //  For POSIX, these are all the same format; slashes and backslashes are as input and
Example #2
0
void
PathBox::SetPath(const entry_ref &ref)
{
	BPath path(&ref);
	fPathControl->SetText(path.Path());
}
Example #3
0
void ui_menu_crosshair::populate()
{
	crosshair_user_settings settings;
	crosshair_item_data *data;
	char temp_text[16];
	int player;
	UINT8 use_auto = false;
	UINT32 flags = 0;

	/* loop over player and add the manual items */
	for (player = 0; player < MAX_PLAYERS; player++)
	{
		/* get the user settings */
		machine().crosshair().get_user_settings(player, &settings);

		/* add menu items for usable crosshairs */
		if (settings.used)
		{
			/* Make sure to keep these matched to the CROSSHAIR_VISIBILITY_xxx types */
			static const char *const vis_text[] = { "Off", "On", "Auto" };

			/* track if we need the auto time menu */
			if (settings.mode == CROSSHAIR_VISIBILITY_AUTO) use_auto = true;

			/* CROSSHAIR_ITEM_VIS - allocate a data item and fill it */
			data = (crosshair_item_data *)m_pool_alloc(sizeof(*data));
			data->type = CROSSHAIR_ITEM_VIS;
			data->player = player;
			data->min = CROSSHAIR_VISIBILITY_OFF;
			data->max = CROSSHAIR_VISIBILITY_AUTO;
			data->defvalue = CROSSHAIR_VISIBILITY_DEFAULT;
			data->cur = settings.mode;

			/* put on arrows */
			if (data->cur > data->min)
				flags |= MENU_FLAG_LEFT_ARROW;
			if (data->cur < data->max)
				flags |= MENU_FLAG_RIGHT_ARROW;

			/* add CROSSHAIR_ITEM_VIS menu */
			sprintf(temp_text, "P%d Visibility", player + 1);
			item_append(temp_text, vis_text[settings.mode], flags, data);

			/* CROSSHAIR_ITEM_PIC - allocate a data item and fill it */
			data = (crosshair_item_data *)m_pool_alloc(sizeof(*data));
			data->type = CROSSHAIR_ITEM_PIC;
			data->player = player;
			data->last_name[0] = 0;
			/* other data item not used by this menu */

			/* search for crosshair graphics */

			/* open a path to the crosshairs */
			file_enumerator path(machine().options().crosshair_path());
			const osd_directory_entry *dir;
			/* reset search flags */
			int using_default = false;
			int finished = false;
			int found = false;

			/* if we are using the default, then we just need to find the first in the list */
			if (*(settings.name) == 0)
				using_default = true;

			/* look for the current name, then remember the name before */
			/* and find the next name */
			while (((dir = path.next()) != nullptr) && !finished)
			{
				int length = strlen(dir->name);

				/* look for files ending in .png with a name not larger then 9 chars*/
				if ((length > 4) && (length <= CROSSHAIR_PIC_NAME_LENGTH + 4) &&
					dir->name[length - 4] == '.' &&
					tolower((UINT8)dir->name[length - 3]) == 'p' &&
					tolower((UINT8)dir->name[length - 2]) == 'n' &&
					tolower((UINT8)dir->name[length - 1]) == 'g')

				{
					/* remove .png from length */
					length -= 4;

					if (found || using_default)
					{
						/* get the next name */
						strncpy(data->next_name, dir->name, length);
						data->next_name[length] = 0;
						finished = true;
					}
					else if (!strncmp(dir->name, settings.name, length))
					{
						/* we found the current name */
						/* so loop once more to find the next name */
						found = true;
					}
					else
						/* remember last name */
						/* we will do it here in case files get added to the directory */
					{
						strncpy(data->last_name, dir->name, length);
						data->last_name[length] = 0;
					}
				}
			}
			/* if name not found then next item is DEFAULT */
			if (!found && !using_default)
			{
				data->next_name[0] = 0;
				finished = true;
			}
			/* setup the selection flags */
			flags = 0;
			if (finished)
				flags |= MENU_FLAG_RIGHT_ARROW;
			if (found)
				flags |= MENU_FLAG_LEFT_ARROW;

			/* add CROSSHAIR_ITEM_PIC menu */
			sprintf(temp_text, "P%d Crosshair", player + 1);
			item_append(temp_text, using_default ? "DEFAULT" : settings.name, flags, data);
		}
	}
	if (use_auto)
	{
		/* any player can be used to get the autotime */
		machine().crosshair().get_user_settings(0, &settings);

		/* CROSSHAIR_ITEM_AUTO_TIME - allocate a data item and fill it */
		data = (crosshair_item_data *)m_pool_alloc(sizeof(*data));
		data->type = CROSSHAIR_ITEM_AUTO_TIME;
		data->min = CROSSHAIR_VISIBILITY_AUTOTIME_MIN;
		data->max = CROSSHAIR_VISIBILITY_AUTOTIME_MAX;
		data->defvalue = CROSSHAIR_VISIBILITY_AUTOTIME_DEFAULT;
		data->cur = settings.auto_time;

		/* put on arrows in visible menu */
		if (data->cur > data->min)
			flags |= MENU_FLAG_LEFT_ARROW;
		if (data->cur < data->max)
			flags |= MENU_FLAG_RIGHT_ARROW;

		/* add CROSSHAIR_ITEM_AUTO_TIME menu */
		sprintf(temp_text, "%d", settings.auto_time);
		item_append("Visible Delay", temp_text, flags, data);
	}
//  else
//      /* leave a blank filler line when not in auto time so size does not rescale */
//      item_append("", "", NULL, NULL);
}
Example #4
0
/// Basic and really simplistic routine to fix malformatted .json files
/// It will replace the old version of your file on success and create a backup of the old one (called <filename>_backup.json)
/// Currently it fixes: double commata, missing " for non-numeric strings
int JSON_Fix(const char *filename)
{
    string s;
    copystring(s, filename);
    const char *found = findfile(path(s), "");
    char *buf = loadfile(found, NULL);
    if(!buf) return -1;
    JSON_Minify(buf);

    size_t len = strlen(buf);

    char *newbuf = new char[len + 1];

    size_t pos = 0; //current position in the newbuf
    for(size_t i = 0; i < len; i++)
    {
        if(buf[i] == ',')
        {
                if(!i) i++;                     //buf starts with a commata
                else if(buf[i + 1] == ',') i++; //two subsequent commata
                else
                {
                    newbuf[pos] = buf[i];
                    pos++;
                }
        }
        else if(isalpha(buf[i]))
        {
            if(!i) //todo worst case: is it an array or object?
                return 0;
            else if(buf[i - 1] != '\"') {
                newbuf[pos] = '\"'; pos++;
            } //string was missing a leading "
            newbuf[pos] = buf[i];
            pos++;
        }
        else
        {
            if(i && isalpha(i - 1)) {
                newbuf[pos] = '\"'; pos++;
            } //string was missing a trailing "
            newbuf[pos] = buf[i];
            pos++;
        }
    }

    JSON *j = JSON_Parse(newbuf);
    if(j)
    {
        conoutf("%s was malformatted but has been fixed automatically. \nThe original file has been overwritten, but backuped", found);
        //cutextension .. getextension
        defformatstring(backupname)("%s_backup", found);
        if(!rename(found, backupname)) j->save(found);
        delete j;
        delete[] buf;
        delete[] newbuf;
        return 1;
    }

    delete[] buf;
    delete[] newbuf;
    return 0;
}
Example #5
0
QgsDataItem *QgsOgrDataItemProvider::createDataItem( const QString &pathIn, QgsDataItem *parentItem )
{
  QString path( pathIn );
  if ( path.isEmpty() )
    return nullptr;

  QgsDebugMsgLevel( "thePath: " + path, 2 );

  // zip settings + info
  QgsSettings settings;
  QString scanZipSetting = settings.value( QStringLiteral( "qgis/scanZipInBrowser2" ), "basic" ).toString();
  QString vsiPrefix = QgsZipItem::vsiPrefix( path );
  bool is_vsizip = ( vsiPrefix == QLatin1String( "/vsizip/" ) );
  bool is_vsigzip = ( vsiPrefix == QLatin1String( "/vsigzip/" ) );
  bool is_vsitar = ( vsiPrefix == QLatin1String( "/vsitar/" ) );

  // should we check ext. only?
  // check if scanItemsInBrowser2 == extension or parent dir in scanItemsFastScanUris
  // TODO - do this in dir item, but this requires a way to inform which extensions are supported by provider
  // maybe a callback function or in the provider registry?
  bool scanExtSetting = false;
  if ( ( settings.value( QStringLiteral( "qgis/scanItemsInBrowser2" ),
                         "extension" ).toString() == QLatin1String( "extension" ) ) ||
       ( parentItem && settings.value( QStringLiteral( "qgis/scanItemsFastScanUris" ),
                                       QStringList() ).toStringList().contains( parentItem->path() ) ) ||
       ( ( is_vsizip || is_vsitar ) && parentItem && parentItem->parent() &&
         settings.value( QStringLiteral( "qgis/scanItemsFastScanUris" ),
                         QStringList() ).toStringList().contains( parentItem->parent()->path() ) ) )
  {
    scanExtSetting = true;
  }

  // get suffix, removing .gz if present
  QString tmpPath = path; //path used for testing, not for layer creation
  if ( is_vsigzip )
    tmpPath.chop( 3 );
  QFileInfo info( tmpPath );
  QString suffix = info.suffix().toLower();
  // extract basename with extension
  info.setFile( path );
  QString name = info.fileName();

  // If a .tab exists, then the corresponding .map/.dat is very likely a
  // side-car file of the .tab
  if ( suffix == QLatin1String( "map" ) || suffix == QLatin1String( "dat" ) )
  {
    if ( QFileInfo( QDir( info.path() ), info.baseName() + ".tab" ).exists() )
      return nullptr;
  }

  QgsDebugMsgLevel( "thePath= " + path + " tmpPath= " + tmpPath + " name= " + name
                    + " suffix= " + suffix + " vsiPrefix= " + vsiPrefix, 3 );

  QStringList myExtensions = fileExtensions();
  QStringList dirExtensions = directoryExtensions();

  // allow only normal files, supported directories, or VSIFILE items to continue
  bool isOgrSupportedDirectory = info.isDir() && dirExtensions.contains( suffix );
  if ( !isOgrSupportedDirectory && !info.isFile() && vsiPrefix.isEmpty() )
    return nullptr;

  // skip *.aux.xml files (GDAL auxiliary metadata files),
  // *.shp.xml files (ESRI metadata) and *.tif.xml files (TIFF metadata)
  // unless that extension is in the list (*.xml might be though)
  if ( path.endsWith( QLatin1String( ".aux.xml" ), Qt::CaseInsensitive ) &&
       !myExtensions.contains( QStringLiteral( "aux.xml" ) ) )
    return nullptr;
  if ( path.endsWith( QLatin1String( ".shp.xml" ), Qt::CaseInsensitive ) &&
       !myExtensions.contains( QStringLiteral( "shp.xml" ) ) )
    return nullptr;
  if ( path.endsWith( QLatin1String( ".tif.xml" ), Qt::CaseInsensitive ) &&
       !myExtensions.contains( QStringLiteral( "tif.xml" ) ) )
    return nullptr;

  // skip QGIS style xml files
  if ( path.endsWith( QLatin1String( ".xml" ), Qt::CaseInsensitive ) &&
       QgsStyle::isXmlStyleFile( path ) )
    return nullptr;

  // We have to filter by extensions, otherwise e.g. all Shapefile files are displayed
  // because OGR drive can open also .dbf, .shx.
  if ( myExtensions.indexOf( suffix ) < 0 && !dirExtensions.contains( suffix ) )
  {
    bool matches = false;
    const auto constWildcards = wildcards();
    for ( const QString &wildcard : constWildcards )
    {
      QRegExp rx( wildcard, Qt::CaseInsensitive, QRegExp::Wildcard );
      if ( rx.exactMatch( info.fileName() ) )
      {
        matches = true;
        break;
      }
    }
    if ( !matches )
      return nullptr;
  }

  // .dbf should probably appear if .shp is not present
  if ( suffix == QLatin1String( "dbf" ) )
  {
    QString pathShp = path.left( path.count() - 4 ) + ".shp";
    if ( QFileInfo::exists( pathShp ) )
      return nullptr;
  }

  // fix vsifile path and name
  if ( !vsiPrefix.isEmpty() )
  {
    // add vsiPrefix to path if needed
    if ( !path.startsWith( vsiPrefix ) )
      path = vsiPrefix + path;
    // if this is a /vsigzip/path_to_zip.zip/file_inside_zip remove the full path from the name
    // no need to change the name I believe
#if 0
    if ( ( is_vsizip || is_vsitar ) && ( path != vsiPrefix + parentItem->path() ) )
    {
      name = path;
      name = name.replace( vsiPrefix + parentItem->path() + '/', "" );
    }
#endif
  }

  // Filters out the OGR/GDAL supported formats that can contain multiple layers
  // and should be treated like a DB: GeoPackage and SQLite
  // NOTE: this formats are scanned for rasters too and they must
  //       be skipped by "gdal" provider or the rasters will be listed
  //       twice. ogrSupportedDbLayersExtensions must be kept in sync
  //       with the companion variable (same name) in the gdal provider
  //       class
  // TODO: add more OGR supported multiple layers formats here!
  static QStringList sOgrSupportedDbLayersExtensions { QStringLiteral( "gpkg" ),
      QStringLiteral( "sqlite" ),
      QStringLiteral( "db" ),
      QStringLiteral( "gdb" ),
      QStringLiteral( "kml" ) };
  static QStringList sOgrSupportedDbDriverNames { QStringLiteral( "GPKG" ),
      QStringLiteral( "db" ),
      QStringLiteral( "gdb" ) };

  // these extensions are trivial to read, so there's no need to rely on
  // the extension only scan here -- avoiding it always gives us the correct data type
  // and sublayer visiblity
  static QStringList sSkipFastTrackExtensions { QStringLiteral( "xlsx" ),
      QStringLiteral( "ods" ),
      QStringLiteral( "csv" ),
      QStringLiteral( "nc" ) };

  // Fast track: return item without testing if:
  // scanExtSetting or zipfile and scan zip == "Basic scan"
  // netCDF files can be both raster or vector, so fallback to opening
  if ( ( scanExtSetting ||
         ( ( is_vsizip || is_vsitar ) && scanZipSetting == QLatin1String( "basic" ) ) ) &&
       !sSkipFastTrackExtensions.contains( suffix ) )
  {
    // if this is a VRT file make sure it is vector VRT to avoid duplicates
    if ( suffix == QLatin1String( "vrt" ) )
    {
      CPLPushErrorHandler( CPLQuietErrorHandler );
      CPLErrorReset();
      GDALDriverH hDriver = GDALIdentifyDriver( path.toUtf8().constData(), nullptr );
      CPLPopErrorHandler();
      if ( !hDriver || GDALGetDriverShortName( hDriver ) == QLatin1String( "VRT" ) )
      {
        QgsDebugMsgLevel( QStringLiteral( "Skipping VRT file because root is not a OGR VRT" ), 2 );
        return nullptr;
      }
    }
    // Handle collections
    // Check if the layer has sublayers by comparing the extension
    QgsDataItem *item = nullptr;
    if ( ! sOgrSupportedDbLayersExtensions.contains( suffix ) )
    {
      item = new QgsOgrLayerItem( parentItem, name, path, path, QgsLayerItem::Vector );
    }
    else if ( suffix.compare( QLatin1String( "gpkg" ), Qt::CaseInsensitive ) == 0 )
    {
      item = new QgsGeoPackageCollectionItem( parentItem, name, path );
    }
    else
    {
      item = new QgsOgrDataCollectionItem( parentItem, name, path );
    }

    if ( item )
      return item;
  }

  // Slow track: scan file contents
  QgsDataItem *item = nullptr;

  // test that file is valid with OGR
  if ( OGRGetDriverCount() == 0 )
  {
    OGRRegisterAll();
  }
  // do not print errors, but write to debug
  CPLPushErrorHandler( CPLQuietErrorHandler );
  CPLErrorReset();
  gdal::dataset_unique_ptr hDS( GDALOpenEx( path.toUtf8().constData(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr ) );
  CPLPopErrorHandler();

  if ( ! hDS )
  {
    QgsDebugMsg( QStringLiteral( "GDALOpen error # %1 : %2 on %3" ).arg( CPLGetLastErrorNo() ).arg( CPLGetLastErrorMsg() ).arg( path ) );
    return nullptr;
  }

  GDALDriverH hDriver = GDALGetDatasetDriver( hDS.get() );
  QString driverName = GDALGetDriverShortName( hDriver );
  QgsDebugMsgLevel( QStringLiteral( "GDAL Driver : %1" ).arg( driverName ), 2 );
  int numLayers = GDALDatasetGetLayerCount( hDS.get() );

  // GeoPackage needs a specialized data item, mainly because of raster deletion not
  // yet implemented in GDAL (2.2.1)
  if ( driverName == QLatin1String( "GPKG" ) )
  {
    item = new QgsGeoPackageCollectionItem( parentItem, name, path );
  }
  else if ( numLayers > 1 || sOgrSupportedDbDriverNames.contains( driverName ) )
  {
    item = new QgsOgrDataCollectionItem( parentItem, name, path );
  }
  else
  {
    item = dataItemForLayer( parentItem, name, path, hDS.get(), 0, false, true );
  }
  return item;
}
Example #6
0
    virtual void on_draw()
    {
        pixfmt pixf(rbuf_window());
        renderer_base rb(pixf);
        renderer_solid r(rb);
        rb.clear(agg::rgba(1, 1, 1));

        scanline_type sl;
        agg::rasterizer_scanline_aa<> ras;

        m_poly.close(m_close.status());
        agg::simple_polygon_vertex_source path(m_poly.polygon(), 
                                               m_poly.num_points(), 
                                               false, 
                                               m_close.status());

        typedef agg::conv_bspline<agg::simple_polygon_vertex_source> conv_bspline_type;
        conv_bspline_type bspline(path);
        bspline.interpolation_step(1.0 / m_num_points.value());

        agg::trans_single_path tcurve;
        tcurve.add_path(bspline);
        tcurve.preserve_x_scale(m_preserve_x_scale.status());
        if(m_fixed_len.status()) tcurve.base_length(1120);

        typedef agg::conv_curve<font_manager_type::path_adaptor_type>            conv_font_curve_type;
        typedef agg::conv_segmentator<conv_font_curve_type>                      conv_font_segm_type;
        typedef agg::conv_transform<conv_font_segm_type, agg::trans_single_path> conv_font_trans_type;
        conv_font_curve_type fcurves(m_fman.path_adaptor());

        conv_font_segm_type  fsegm(fcurves);
        conv_font_trans_type ftrans(fsegm, tcurve);
        fsegm.approximation_scale(3.0);
        fcurves.approximation_scale(2.0);

        if(m_feng.load_font(full_file_name("timesi.ttf"), 0, agg::glyph_ren_outline))
        {
            double x = 0.0;
            double y = 3.0;
            const char* p = text;

            m_feng.hinting(false);
            m_feng.height(40);

            while(*p)
            {
                const agg::glyph_cache* glyph = m_fman.glyph(*p);
                if(glyph)
                {
                    if(x > tcurve.total_length()) break;

                    m_fman.add_kerning(&x, &y);
                    m_fman.init_embedded_adaptors(glyph, x, y);

                    if(glyph->data_type == agg::glyph_data_outline)
                    {
                        ras.reset();
                        ras.add_path(ftrans);
                        r.color(agg::srgba8(0, 0, 0));
                        agg::render_scanlines(ras, sl, r);
                    }

                    // increment pen position
                    x += glyph->advance_x;
                    y += glyph->advance_y;
                }
                ++p;
            }
        }
        else
        {
            message("Please copy file timesi.ttf to the current directory\n"
                    "or download it from http://www.antigrain.com/timesi.zip");
        }



        typedef agg::conv_stroke<conv_bspline_type> conv_stroke_type;
        conv_stroke_type stroke(bspline);

        stroke.width(2.0);

        r.color(agg::srgba8(170, 50, 20, 100));
        ras.add_path(stroke);
        agg::render_scanlines(ras, sl, r);

        //--------------------------
        // Render the "poly" tool and controls
        r.color(agg::rgba(0, 0.3, 0.5, 0.3));
        ras.add_path(m_poly);
        agg::render_scanlines(ras, sl, r);

        agg::render_ctrl(ras, sl, rb, m_close);
        agg::render_ctrl(ras, sl, rb, m_preserve_x_scale);
        agg::render_ctrl(ras, sl, rb, m_fixed_len);
        agg::render_ctrl(ras, sl, rb, m_animate);
        agg::render_ctrl(ras, sl, rb, m_num_points);
        //--------------------------

    }
//*************************************************************************************************
// MAIN
//*************************************************************************************************
int main(int argc, char* argv[])
{
   ossimString tempString;
   double tempDouble, tempDouble2;
   ossimArgumentParser::ossimParameter stringParam(tempString);
   ossimArgumentParser::ossimParameter doubleParam(tempDouble);
   ossimArgumentParser::ossimParameter doubleParam2(tempDouble2);

   ossimArgumentParser argumentParser(&argc, argv);
   ossimInit::instance()->addOptions(argumentParser);
   ossimInit::instance()->initialize(argumentParser);

   argumentParser.getApplicationUsage()->setApplicationName(argumentParser.getApplicationName());
   argumentParser.getApplicationUsage()->setDescription(argumentParser.getApplicationName()+
      " Generates a bit-mask given source image and target pixel range to mask out. If the input"
      " image has overviews, then masks will be generated for all R-levels.");
   argumentParser.getApplicationUsage()->setCommandLineUsage(argumentParser.getApplicationName()+
      " [options] <input file>");

   argumentParser.getApplicationUsage()->addCommandLineOption("-d", 
      "Write mask to directory specified.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-e or --entry",
      "Give the entry(zero based) for which to build a mask. Only one entry can be processed. "
      "If the input is multi-entry and no entry was specified, entry 0 is assumed.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-h or --help", 
      "Shows help");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-mode <mode>",
      "Specifies how to treat multi-band imagery when determining whether pixel will be masked "
      "according to the defined target value or range. Possible modes are: "
      "\"mask_full_and_partial_targets\" (default) | \"mask_only_full_targets\".");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-range <min> <max>", 
      "Specifies the range of pixels to target for masking out.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--mask-value <target>", 
      "Specifies the unique pixel value to target for masking out.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-o", 
      "Write mask to file specified.  If used on a multi-entry file, given \"foo.mask\" you will "
      "get: \"foo_e0.mask\". If none specified, the input filename is used with \".mask\" "
      "extension.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--ovr-from-image", 
      "Uses exclusively the image overview data when computing subsequent overviews. "
      "Normally the mask overview from the prior level is referenced for establishing the masks at "
      "the next level.");

   argumentParser.getApplicationUsage()->addCommandLineOption("--spec-kwl <filename>", 
      "In lieu of providing mask parameters on the command line, this option specifies a keyword "
      "list filename that contains all settings. Typically used when spawning from other process.");

   argumentParser.getApplicationUsage()->addCommandLineOption("-x or --exclude-fullres", 
      "Excludes R0 mask computation. The mask file will start at R1.");

   if(argumentParser.read("-h") || argumentParser.read("--help"))
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      finalize(0);
   }

   if ( argumentParser.read("--version") || argumentParser.read("-v"))
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " 
         << ossimInit::instance()->instance()->version().c_str()<< std::endl;
      finalize(0);
   }

   // Fetch command line options:
   ossimFilename outputFile;
   if (argumentParser.read("-o", stringParam))
      outputFile = tempString.trim();

   ossimFilename outputDir;
   if (argumentParser.read("-d", stringParam))
      outputDir = tempString.trim();

   bool exclude_r0 = false;
   if (argumentParser.read("-x") || argumentParser.read("--exclude-fullres"))
      exclude_r0 = true;

   bool entry_specified = false;
   ossim_int32 entry = 0;
   if (argumentParser.read("-e", stringParam) || argumentParser.read("--entry", stringParam))
   {
      entry = ossimString(tempString).toUInt32();
      entry_specified = true;
   }

   double target_min = 0;
   double target_max = 0;
   if (argumentParser.read("--mask-range", doubleParam, doubleParam2))
   {
      target_min = tempDouble;
      target_max = tempDouble2;
   }

   if (argumentParser.read("--mask-value", doubleParam))
   {
      target_min = tempDouble;
      target_max = target_min;
   }

   ossimString mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET";
   ossimString mask_mode_arg;
   if (argumentParser.read("--mask-mode", stringParam))
   {
      mask_mode_arg = tempString;
      if (mask_mode_arg == "mask_full_and_partial_targets")
         mask_mode = "REPLACE_ALL_BANDS_IF_ANY_TARGET";
      else if (mask_mode_arg == "mask_only_full_targets")
         mask_mode = "REPLACE_ONLY_FULL_TARGETS";
      else
      {
         ossimNotify(ossimNotifyLevel_NOTICE)<< argumentParser.getApplicationName().c_str() << " " 
            << " Unknown mask-mode <"<<mask_mode_arg<<"> specified. See usage below." << std::endl;
         argumentParser.getApplicationUsage()->write(std::cout);
         finalize(1);
      }
   }

   bool ovr_from_image = false;
   if (argumentParser.read("--ovr-from-image"))
      ovr_from_image = true;

   ossimFilename spec_kwl_file;
   if (argumentParser.read("--spec_kwl", stringParam))
      spec_kwl_file = tempString.trim();

   // Handle bad command line:
   argumentParser.reportRemainingOptionsAsUnrecognized();
   if (argumentParser.errors())
   {
      argumentParser.writeErrorMessages(std::cout);
      finalize(1);
   }
   if ((argumentParser.argc()<2) && spec_kwl_file.empty())
   {
      argumentParser.getApplicationUsage()->write(std::cout);
      finalize(1);
   }

   // Establish input filename:
   ossimFilename inputFile;
   ossimKeywordlist kwl;
   if (spec_kwl_file.isReadable())
   {
      kwl.addFile(spec_kwl_file);
      inputFile = kwl.find(ossimKeywordNames::IMAGE_FILE_KW);
      outputFile = kwl.find(ossimKeywordNames::OUTPUT_FILE_KW);
   }
   else
   {
      inputFile = argv[1];
   }

   // Establish the input image handler:
   ossimRefPtr<ossimImageHandler> handler = ossimImageHandlerRegistry::instance()->open(inputFile);
   if (!handler.valid())
   {
      ossimNotify(ossimNotifyLevel_FATAL)<<argumentParser.getApplicationName().c_str()
         <<" Error encountered opening input file <"<<inputFile<<">."<<endl;
      finalize(1);
   }

   // Establish output filename:
   if (outputFile.empty())
      outputFile = handler->getFilenameWithThisExtension("mask", entry_specified);
   if (!outputDir.empty())
      outputFile.setPath(outputDir);
   else
   {
      ossimFilename path (outputFile.path());
      if (path.empty())
         outputFile.setPath(inputFile.path());
   }

   // Consider input file with multiple entries:
   std::vector<ossim_uint32> entryList;
   handler->getEntryList(entryList); 
   if (entryList.size() <= entry)
   {
      ossimNotify(ossimNotifyLevel_FATAL)<<argumentParser.getApplicationName().c_str()
         <<" Entry specified <"<<entry<<"> exceeds total number of entries available <"
         <<entryList.size()<<">. Aborting..."<<endl;
      finalize(1);
   }
   handler->setCurrentEntry(entry); 


   // Establish a keywordlist to pass to the mask builder. This KWL may have already been specified
   // on the command line with --spec_kwl option:
   kwl.add(ossimKeywordNames::OUTPUT_FILE_KW, outputFile.chars()); // may overwrite same value
   if (kwl.getSize() == 0)
   {
      kwl.add(ossimKeywordNames::IMAGE_FILE_KW, inputFile.chars());
      ossimString target_str (ossimString::toString(target_min)+" "+ossimString::toString(target_max));
      kwl.add(ossimPixelFlipper::PF_TARGET_RANGE_KW, target_str.chars());
      kwl.add(ossimPixelFlipper::PF_REPLACEMENT_MODE_KW, mask_mode.chars());
      kwl.add(ossimPixelFlipper::PF_REPLACEMENT_VALUE_KW, (int) 0);
      if (exclude_r0)
         kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 1);
      else
         kwl.add(ossimBitMaskWriter::BM_STARTING_RLEVEL_KW, (int) 0);
   }

   // Instantiate the bit mask processor and write out the mask file:
   ossimRefPtr<ossimBitMaskWriter> mask_writer = new ossimBitMaskWriter;
   mask_writer->loadState(kwl);
   mask_writer->connectMyInputTo(handler.get());

   // Need to loop over all R-levels. Use a sequencer:
   ossimRefPtr<ossimImageSourceSequencer> sequencer =  new ossimImageSourceSequencer(handler.get());
   sequencer->initialize();
   int num_rlevels = handler->getNumberOfDecimationLevels();
   int num_tiles = sequencer->getNumberOfTiles();
   int tile_idx = 0;
   int percent_complete = 0;
   ossimRefPtr<ossimImageData> tile = 0;

   int start_res = 0;
   if (exclude_r0)
   {
      start_res = 1;
      num_tiles = (num_tiles+3)/4;
   }

   for (int r=start_res; r<num_rlevels; r++)
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<<"\nProcessing R-level "<<r<<"... "<<endl;

      // Set the area of interest to the full image rectangle at this R-level:
      ossimIrect rect (handler->getBoundingRect(r));
      sequencer->setAreaOfInterest(rect);
      sequencer->setToStartOfSequence();
      do
      {
         tile = sequencer->getNextTile(r);
         mask_writer->generateMask(tile, r);

         percent_complete = 100 * tile_idx++/num_tiles;
         ossimNotify(ossimNotifyLevel_NOTICE)<<percent_complete<< "%\r";
      } 
      while(tile.valid());
      tile_idx = 0;
      num_tiles = (num_tiles+3)/4;
      if (num_tiles == 0)
         num_tiles = 1;

      // Check if additional overviews are to be generated directly from the mask at first R-level:
      if ((r == start_res) && !ovr_from_image)
      {
         ossimNotify(ossimNotifyLevel_NOTICE)<<"\nBuilding remaining overviews from initial mask..."
            <<endl;
         mask_writer->buildOverviews(num_rlevels);
         break;
      }
   }

   // Finished sequencing all levels, ready to write out the mask buffers:
   mask_writer->close();
   ossimNotify(ossimNotifyLevel_NOTICE)<<"\nSuccessfully wrote mask file to <"<<outputFile
      <<">. Finished."<<endl;
   
   finalize(0);
}
Example #8
0
// (static) For a given IShellLink, create and return a populated nsIJumpListShortcut.
nsresult JumpListShortcut::GetJumpListShortcut(IShellLinkW *pLink, nsCOMPtr<nsIJumpListShortcut>& aShortcut)
{
    NS_ENSURE_ARG_POINTER(pLink);

    nsresult rv;
    HRESULT hres;

    nsCOMPtr<nsILocalHandlerApp> handlerApp =
        do_CreateInstance(NS_LOCALHANDLERAPP_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    PRUnichar buf[MAX_PATH];

    // Path
    hres = pLink->GetPath((LPWSTR)&buf, MAX_PATH, NULL, SLGP_UNCPRIORITY);
    if (FAILED(hres))
        return NS_ERROR_INVALID_ARG;

    nsCOMPtr<nsILocalFile> file;
    nsDependentString filepath(buf);
    rv = NS_NewLocalFile(filepath, PR_FALSE, getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = handlerApp->SetExecutable(file);
    NS_ENSURE_SUCCESS(rv, rv);

    // Parameters
    hres = pLink->GetArguments((LPWSTR)&buf, MAX_PATH);
    if (SUCCEEDED(hres)) {
        LPWSTR *arglist;
        PRInt32 numArgs;
        PRInt32 idx;

        arglist = ::CommandLineToArgvW(buf, &numArgs);
        if(arglist) {
            for (idx = 0; idx < numArgs; idx++) {
                // szArglist[i] is null terminated
                nsDependentString arg(arglist[idx]);
                handlerApp->AppendParameter(arg);
            }
            ::LocalFree(arglist);
        }
    }

    rv = aShortcut->SetApp(handlerApp);
    NS_ENSURE_SUCCESS(rv, rv);

    // Icon index or file location
    int iconIdx = 0;
    hres = pLink->GetIconLocation((LPWSTR)&buf, MAX_PATH, &iconIdx);
    if (SUCCEEDED(hres)) {
        // XXX How do we handle converting local files to images here? Do we need to?
        aShortcut->SetIconIndex(iconIdx);

        // Obtain the local profile directory and construct the output icon file path
        // We only set the Icon Uri if we're sure it was from our icon cache.
        PRBool isInOurCache;
        if (NS_SUCCEEDED(IsPathInOurIconCache(aShortcut, buf, &isInOurCache)) &&
                isInOurCache) {
            nsCOMPtr<nsIURI> iconUri;
            nsAutoString path(buf);
            rv = NS_NewURI(getter_AddRefs(iconUri), path);
            if (NS_SUCCEEDED(rv)) {
                aShortcut->SetFaviconPageUri(iconUri);
            }
        }
    }

    // Do we need the title and description? Probably not since handler app doesn't compare
    // these in equals.

    return NS_OK;
}
Example #9
0
void MergeRootfile( TDirectory *target, TList *sourcelist) {

  //  cout << "Target path: " << target->GetPath() << endl;
  TString path( (char*)strstr( target->GetPath(), ":" ) );
  path.Remove( 0, 2 );

  TFile *first_source = (TFile*)sourcelist->First();

  first_source->cd( path );
  TDirectory *current_sourcedir = gDirectory;
  //gain time, do not add the objects in the list in memory
  Bool_t status = TH1::AddDirectoryStatus();
  TH1::AddDirectory(kFALSE);

  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key, *oldkey=0;
  std::vector<double>::iterator wItr;

  while ( (key = (TKey*)nextkey())) {
    wItr=WeightList->begin();

    //keep only the highest cycle number for each key
    if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;

    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();

    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> merge it

      //      cout << "Merging histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;
      h1->Sumw2();

      // weight is eff * sigma, because the histos are produced on the ~same initial
      // events, and eff is already included (in reconstruction), weight is just sigma
      h1->Scale(double(*wItr));
  
      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      wItr++;
      while ( nextsource ) {
        
        // make sure we are at the correct directory level by cd'ing to path
        nextsource->cd( path );
        TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
        if (key2) {
           TH1 *h2 = (TH1*)key2->ReadObj();
	   h2->Sumw2();
	   h2->Scale( double(*wItr) );
           h1->Add( h2 );
           delete h2;
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
	wItr++;
      }
    }
    else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {
      
      // loop over all source files create a chain of Trees "globChain"
      const char* obj_name= obj->GetName();

      globChain = new TChain(obj_name);
      globChain->Add(first_source->GetName());
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      //      const char* file_name = nextsource->GetName();
      // cout << "file name  " << file_name << endl;
     while ( nextsource ) {
     	  
       globChain->Add(nextsource->GetName());
       nextsource = (TFile*)sourcelist->After( nextsource );
     }

    } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
      // it's a subdirectory

      cout << "Found subdirectory " << obj->GetName() << endl;

      // create a new subdir of same name and title in the target file
      target->cd();
      TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );

      // newdir is now the starting point of another round of merging
      // newdir still knows its depth within the target file via
      // GetPath(), so we can still figure out where we are in the recursion
      MergeRootfile( newdir, sourcelist );

    } else {

      // object is of no type that we know or can handle
      cout << "Unknown object type, name: " 
           << obj->GetName() << " title: " << obj->GetTitle() << endl;
    }

    // now write the merged histogram (which is "in" obj) to the target file
    // note that this will just store obj in the current directory level,
    // which is not persistent until the complete directory itself is stored
    // by "target->Write()" below
    if ( obj ) {
      target->cd();

      //!!if the object is a tree, it is stored in globChain...
	if(obj->IsA()->InheritsFrom( "TTree" ))
          globChain->Merge(target->GetFile(),0,"keep");
	else
	obj->Write( key->GetName() );
    }

  } // while ( ( TKey *key = (TKey*)nextkey() ) )

  // save modifications to target file
  target->SaveSelf(kTRUE);
  TH1::AddDirectory(status);
}
Example #10
0
void EraserTool::drawStroke()
{
    StrokeTool::drawStroke();
    QList<QPointF> p = m_pStrokeManager->interpolateStroke(currentWidth);

    Layer *layer = m_pEditor->getCurrentLayer();

    if (layer->type == Layer::BITMAP)
    {
        for (int i = 0; i < p.size(); i++) {
            p[i] = m_pScribbleArea->pixelToPoint(p[i]);
        }

        qreal opacity = 1.0;
        qreal brushWidth = currentWidth +  0.5 * properties.feather;
        qreal offset = qMax(0.0, currentWidth - 0.5 * properties.feather) / brushWidth;
        opacity = currentPressure;
        brushWidth = brushWidth * currentPressure;

        //        if (tabletInUse) { opacity = tabletPressure; }
        //        if (usePressure) { brushWidth = brushWidth * tabletPressure; }

        qreal brushStep = 0.5 * currentWidth + 0.5 * properties.feather;
        brushStep = brushStep * currentPressure;

        //        if (usePressure) { brushStep = brushStep * tabletPressure; }
        brushStep = qMax(1.0, brushStep);

        currentWidth = properties.width;
        BlitRect rect;

        QRadialGradient radialGrad(QPointF(0,0), 0.5 * brushWidth);
        m_pScribbleArea->setGaussianGradient(radialGrad, QColor(255,255,255), opacity, offset);

        QPointF a = lastBrushPoint;
        QPointF b = getCurrentPoint();

        //        foreach (QSegment segment, calculateStroke(brushWidth))
        //        {
        //            QPointF a = lastBrushPoint;
        //            QPointF b = m_pScribbleArea->pixelToPoint(segment.second);

        qreal distance = 4 * QLineF(b, a).length();
        int steps = qRound(distance) / brushStep;

        for (int i = 0; i < steps; i++)
        {
            QPointF point = lastBrushPoint + (i + 1) * (brushStep) * (b - lastBrushPoint) / distance;
            rect.extend(point.toPoint());
            m_pScribbleArea->drawBrush(point, brushWidth, offset, QColor(255,255,255), opacity);

            if (i == (steps - 1))
            {
                lastBrushPoint = point;
            }
        }
        //        }

        int rad = qRound(brushWidth) / 2 + 2;
        m_pScribbleArea->refreshBitmap(rect, rad);
    }
    else if (layer->type == Layer::VECTOR)
    {
        QPen pen(Qt::white, currentWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
        int rad = qRound((currentWidth / 2 + 2) * (qAbs(m_pScribbleArea->getTempViewScaleX()) + qAbs(m_pScribbleArea->getTempViewScaleY())));

        if (p.size() == 4) {
            QSizeF size(2,2);
            QPainterPath path(p[0]);
            path.cubicTo(p[1],
                p[2],
                p[3]);
            m_pScribbleArea->drawPath(path, pen, Qt::NoBrush, QPainter::CompositionMode_Source);
            m_pScribbleArea->refreshVector(path.boundingRect().toRect(), rad);
        }
    }
}
Example #11
0
int VtModelParser::LoadCooked(
	const xtime::TimeSlice &time,
	Engine &engine,
	const pkg::Asset::Ref &asset,
	int flags
) {
	if (m_state == kS_None) {
#if defined(RAD_OPT_TOOLS)
		if (!asset->cooked) {
			const String *s = asset->entry->KeyValue<String>("AnimStates.Source", P_TARGET_FLAGS(flags));
			if (!s)
				return SR_MetaError;

			m_statesRef = engine.sys->packages->Resolve(s->c_str, asset->zone);
			if (!m_statesRef)
				return SR_FileNotFound;

			int r = m_statesRef->Process(
				xtime::TimeSlice::Infinite,
				flags
			);

			if (r != SR_Success)
				return r;

			m_states = SkAnimStatesParser::Cast(m_statesRef);
			if (!m_states || !m_states->valid)
				return SR_ParseError;
		} else {
#endif
		const Package::Entry::Import *import = asset->entry->Resolve(0);
		if (!import)
			return SR_MetaError;

		m_statesRef = asset->entry->Resolve(*import, asset->zone);
		if (!m_statesRef)
			return SR_FileNotFound;

		int r = m_statesRef->Process(
			xtime::TimeSlice::Infinite,
			flags
		);

		if (r != SR_Success)
			return r;

		m_states = SkAnimStatesParser::Cast(m_statesRef);
		if (!m_states || !m_states->valid)
			return SR_ParseError;
#if defined(RAD_OPT_TOOLS)
		}
#endif

		m_state = kS_Load0;
	}

	if (m_state == kS_Load0) {
		if (!m_mm[0]) {
#if defined(RAD_OPT_TOOLS)
			if (!asset->cooked) {
				m_cooker = asset->AllocateIntermediateCooker();
				CookStatus status = m_cooker->Status(P_TARGET_FLAGS(flags));

				if (status == CS_Ignore)
					return SR_CompilerError;

				if (status == CS_NeedRebuild) {
					COut(C_Info) << asset->path.get() << " is out of date, rebuilding..." << std::endl;
					int r = m_cooker->Cook(P_TARGET_FLAGS(flags));
					if (r != SR_Success)
						return r;
				} else {
					COut(C_Info) << asset->path.get() << " is up to date, using cache." << std::endl;
				}

				String path(CStr(asset->path));
				path += ".0.bin";

				m_mm[0] = m_cooker->MapFile(path.c_str, r::ZSkm);
				if (!m_mm[0])
					return SR_FileNotFound;
			}
			else {
#endif
			String path(CStr("Cooked/"));
			path += CStr(asset->path);
			path += ".0.bin";

			m_mm[0] = engine.sys->files->MapFile(path.c_str, r::ZSkm);
			if (!m_mm[0])
				return SR_FileNotFound;
#if defined(RAD_OPT_TOOLS)
			}
#endif
		}

		m_state = kS_Load1;
	}

	if (m_state == kS_Load1) {
		if (!m_mm[1]) {
#if defined(RAD_OPT_TOOLS)
			if (!asset->cooked)
			{
				String path(CStr(asset->path));
				path += ".1.bin";

				m_mm[1] = m_cooker->MapFile(path.c_str, r::ZSkm);
				m_cooker.reset();

				if (!m_mm[1])
					return SR_FileNotFound;
			}
			else {
#endif
			String path(CStr("Cooked/"));
			path += asset->path.get();
			path += ".1.bin";

			m_mm[1] = engine.sys->files->MapFile(path.c_str, r::ZSkm);
			if (!m_mm[1])
				return SR_FileNotFound;
#if defined(RAD_OPT_TOOLS)
			}
#endif
		}

		const void *data[2];
		AddrSize size[2];

		data[0] = m_mm[0]->data;
		data[1] = m_mm[1]->data;
		size[0] = m_mm[0]->size;
		size[1] = m_mm[1]->size;

		int r = m_dvtm.Parse(data, size);
		if (r < SR_Success)
			return r;

		m_state = kS_Done;
	}

	return SR_Success;
}
Example #12
0
 int compare(const value_type* s) const  { return compare(path(s)); }
Example #13
0
 int compare(const std::string& s) const { return compare(path(s)); }
Example #14
0
 path& operator/=(string_type& s)       { return this->operator/=(path(s)); }
Example #15
0
File: send.c Project: dscho/nmh
int
main (int argc, char **argv)
{
    int msgp = 0, distsw = 0, vecp;
    int isdf = 0, mime = 0;
    int msgnum, status;
    char *cp, *dfolder = NULL, *maildir = NULL;
    char buf[BUFSIZ], **ap, **argp, **arguments, *program;
    char *msgs[MAXARGS], **vec;
    struct msgs *mp;
    struct stat st;

    if (nmh_init(argv[0], 1)) { return 1; }

    arguments = getarguments (invo_name, argc, argv, 1);
    argp = arguments;

    vec = argsplit(postproc, &program, &vecp);

    vec[vecp++] = "-library";
    vec[vecp++] = getcpy (m_maildir (""));

    if ((cp = context_find ("fileproc"))) {
	vec[vecp++] = "-fileproc";
	vec[vecp++] = cp;
    }

    if ((cp = context_find ("mhlproc"))) {
	vec[vecp++] = "-mhlproc";
	vec[vecp++] = cp;
    }

    if ((cp = context_find ("credentials"))) {
	/* post doesn't read context so need to pass credentials. */
	vec[vecp++] = "-credentials";
	vec[vecp++] = cp;
    }

    while ((cp = *argp++)) {
	if (*cp == '-') {
	    switch (smatch (++cp, switches)) {
		case AMBIGSW: 
		    ambigsw (cp, switches);
		    done (1);
		case UNKWNSW: 
		    adios (NULL, "-%s unknown\n", cp);

		case HELPSW: 
		    snprintf (buf, sizeof(buf), "%s [file] [switches]", invo_name);
		    print_help (buf, switches, 1);
		    done (0);
		case VERSIONSW:
		    print_version(invo_name);
		    done (0);

		case DRAFTSW: 
		    msgs[msgp++] = draft;
		    continue;

		case DFOLDSW: 
		    if (dfolder)
			adios (NULL, "only one draft folder at a time!");
		    if (!(cp = *argp++) || *cp == '-')
			adios (NULL, "missing argument to %s", argp[-2]);
		    dfolder = path (*cp == '+' || *cp == '@' ? cp + 1 : cp,
			    *cp != '@' ? TFOLDER : TSUBCWF);
		    continue;
		case DMSGSW: 
		    if (!(cp = *argp++) || *cp == '-')
			adios (NULL, "missing argument to %s", argp[-2]);
		    msgs[msgp++] = cp;
		    continue;
		case NDFLDSW: 
		    dfolder = NULL;
		    isdf = NOTOK;
		    continue;

		case PUSHSW: 
		    pushsw++;
		    continue;
		case NPUSHSW: 
		    pushsw = 0;
		    continue;

		case SPLITSW: 
		    if (!(cp = *argp++) || sscanf (cp, "%d", &splitsw) != 1)
			adios (NULL, "missing argument to %s", argp[-2]);
		    continue;

		case UNIQSW: 
		    unique++;
		    continue;
		case NUNIQSW: 
		    unique = 0;
		    continue;

		case FORWSW:
		    forwsw++;
		    continue;
		case NFORWSW:
		    forwsw = 0;
		    continue;

		case VERBSW: 
		    verbsw++;
		    vec[vecp++] = --cp;
		    continue;
		case NVERBSW:
		    verbsw = 0;
		    vec[vecp++] = --cp;
		    continue;

		case MIMESW:
		    mime++;
		    vec[vecp++] = --cp;
		    continue;
		case NMIMESW:
		    mime = 0;
		    vec[vecp++] = --cp;
		    continue;

		case DEBUGSW: 
		    debugsw++;	/* fall */
		case NFILTSW: 
		case FRMTSW: 
		case NFRMTSW: 
		case BITSTUFFSW:
		case NBITSTUFFSW:
		case MSGDSW: 
		case NMSGDSW: 
		case WATCSW: 
		case NWATCSW: 
		case SNOOPSW: 
		case SASLSW:
		case NOSASLSW:
		case TLSSW:
		case INITTLSSW:
		case NTLSSW:
		    vec[vecp++] = --cp;
		    continue;

		case ALIASW: 
		case FILTSW: 
		case WIDTHSW: 
		case CLIESW: 
		case SERVSW: 
		case SASLMECHSW:
		case SASLMXSSFSW:
		case USERSW:
		case PORTSW:
		case MTSSW:
		case MESSAGEIDSW:
		    vec[vecp++] = --cp;
		    if (!(cp = *argp++) || *cp == '-')
			adios (NULL, "missing argument to %s", argp[-2]);
		    vec[vecp++] = cp;
		    continue;
		
		case ATTACHSW:
		    advise(NULL, "The -attach switch is deprecated");
		    continue;
		case NOATTACHSW:
		    advise(NULL, "The -noattach switch is deprecated");
		    continue;

		case ATTACHFORMATSW:
		    advise(NULL, "The -attachformat switch is deprecated");
		    continue;
	    }
	} else {
	    msgs[msgp++] = cp;
	}
    }

    /*
     * check for "Aliasfile:" profile entry
     */
    if ((cp = context_find ("Aliasfile"))) {
	char *dp = NULL;

	for (ap = brkstring(dp = getcpy(cp), " ", "\n"); ap && *ap; ap++) {
	    vec[vecp++] = "-alias";
	    vec[vecp++] = *ap;
	}
    }

    if (dfolder == NULL) {
	if (msgp == 0) {
	    msgs[msgp++] = getcpy (m_draft (NULL, NULL, 1, &isdf));
	    if (stat (msgs[0], &st) == NOTOK)
		adios (msgs[0], "unable to stat draft file");
	    cp = concat ("Use \"", msgs[0], "\"? ", NULL);
	    for (status = LISTDSW; status != YESW;) {
		if (!(argp = getans (cp, anyl)))
		    done (1);
		switch (status = smatch (*argp, anyl)) {
		    case NOSW: 
			done (0);
		    case YESW: 
			break;
		    case LISTDSW: 
			showfile (++argp, msgs[0]);
			break;
		    default:
			advise (NULL, "say what?");
			break;
		}
	    }
	} else {
	    for (msgnum = 0; msgnum < msgp; msgnum++)
		msgs[msgnum] = getcpy (m_maildir (msgs[msgnum]));
	}
    } else {
	if (!context_find ("path"))
	    free (path ("./", TFOLDER));

	if (!msgp)
	    msgs[msgp++] = "cur";
	maildir = m_maildir (dfolder);

	if (chdir (maildir) == NOTOK)
	    adios (maildir, "unable to change directory to");

	/* read folder and create message structure */
	if (!(mp = folder_read (dfolder, 1)))
	    adios (NULL, "unable to read folder %s", dfolder);

	/* check for empty folder */
	if (mp->nummsg == 0)
	    adios (NULL, "no messages in %s", dfolder);

	/* parse all the message ranges/sequences and set SELECTED */
	for (msgnum = 0; msgnum < msgp; msgnum++)
	    if (!m_convert (mp, msgs[msgnum]))
		done (1);
	seq_setprev (mp);	/* set the previous-sequence */

	for (msgp = 0, msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	    if (is_selected (mp, msgnum)) {
		msgs[msgp++] = getcpy (m_name (msgnum));
		unset_exists (mp, msgnum);
	    }
	}

	mp->msgflags |= SEQMOD;
	seq_save (mp);
    }

#ifdef WHATNOW
go_to_it:
#endif /* WHATNOW */

    if ((cp = getenv ("SIGNATURE")) == NULL || *cp == 0)
	if ((cp = context_find ("signature")) && *cp)
	    m_putenv ("SIGNATURE", cp);

    for (msgnum = 0; msgnum < msgp; msgnum++)
	if (stat (msgs[msgnum], &st) == NOTOK)
	    adios (msgs[msgnum], "unable to stat draft file");

    if ((annotext = getenv ("mhannotate")) == NULL || *annotext == 0)
	annotext = NULL;
    if (annotext && ((cp = getenv ("mhinplace")) != NULL && *cp != 0))
	inplace = atoi (cp);
    if ((altmsg = getenv ("mhaltmsg")) == NULL || *altmsg == 0)
	altmsg = NULL;	/* used by dist interface - see below */

    if ((cp = getenv ("mhdist"))
	    && *cp
	    && (distsw = atoi (cp))
	    && altmsg) {
	vec[vecp++] = "-dist";
	if ((cp = m_mktemp2(altmsg, invo_name, NULL, NULL)) == NULL) {
	    adios(NULL, "unable to create temporary file in %s",
		  get_temp_dir());
	}
	distfile = getcpy (cp);
	(void) m_unlink(distfile);
	if (link (altmsg, distfile) == NOTOK) {
	    /* Cygwin with FAT32 filesystem produces EPERM. */
	    if (errno != EXDEV  &&  errno != EPERM
#ifdef EISREMOTE
		    && errno != EISREMOTE
#endif /* EISREMOTE */
		)
		adios (distfile, "unable to link %s to", altmsg);
	    free (distfile);
	    if ((cp = m_mktemp2(NULL, invo_name, NULL, NULL)) == NULL) {
		adios(NULL, "unable to create temporary file in %s",
		      get_temp_dir());
	    }
	    distfile = getcpy (cp);
	    {
		int in, out;
		struct stat st;

		if ((in = open (altmsg, O_RDONLY)) == NOTOK)
		    adios (altmsg, "unable to open");
		fstat(in, &st);
		if ((out = creat (distfile, (int) st.st_mode & 0777)) == NOTOK)
		    adios (distfile, "unable to write");
		cpydata (in, out, altmsg, distfile);
		close (in);
		close (out);
	    }	
	}
    } else {
	distfile = NULL;
    }

    if (altmsg == NULL || stat (altmsg, &st) == NOTOK) {
	st.st_mtime = 0;
	st.st_dev = 0;
	st.st_ino = 0;
    }
    if (pushsw)
	push ();

    status = 0;
    closefds (3);

    for (msgnum = 0; msgnum < msgp; msgnum++) {
	switch (sendsbr (vec, vecp, program, msgs[msgnum], &st, 1)) {
	    case DONE: 
		done (++status);
	    case NOTOK: 
		status++;	/* fall */
	    case OK:
		break;
	}
    }

    context_save ();	/* save the context file */
    done (status);
    return 1;
}
Example #16
0
bool _restore(const std::string &project_name,
              const std::string &storage_path, const std::string &history_path)
{
    std::list<file_info> patch_list;
    std::list<file_info> deletion_list;
    std::list<file_info> addition_list;
    std::list<file_info>::iterator iter;
    size_t index;

    if(!_read_list(history_path + "/patch_list", &patch_list))
        return false;
    if(!_read_list(history_path + "/deletion_list", &deletion_list))
        return false;
    if(!_read_list(history_path + "/addition_list", &addition_list))
        return false;

    //rsync patch
    index = 0;
    for(iter = patch_list.begin(); iter != patch_list.end(); ++iter)
    {
        std::string basis;
        std::string patch;
        std::string output;

        basis = storage_path + "/" + iter->path;
        patch = history_path + "/patch." + size2string(index);
        output = project_name + "/tmp_ffbackup";
        if(rsync_patch(basis, patch, output) == false)
        {
            rm_recursive(output);
            return false;
        }
        if(rename(output.c_str(), basis.c_str()) < 0)
        {
            rm_recursive(output);
            return false;
        }
        ++index;
    }

    //process deletion list
    for(iter = deletion_list.begin(); iter != deletion_list.end(); ++iter)
    {
        rm_recursive(storage_path + "/" + iter->path);
    }

    //process addition list
    index = 0;
    for(iter = addition_list.begin(); iter != addition_list.end(); ++iter)
    {
        std::string path(storage_path + "/" + iter->path);
        bool ok;

        if(iter->type == 'f')
            ok = link_or_copy(history_path + "/" + size2string(index), path);
        else if(iter->type == 'd')
            ok = (0 == mkdir(path.c_str(), 0775));
        else
            ok = false;
        if(!ok)
            return false;
        ++index;
    }
    return true;
}
Example #17
0
//! @brief Initializes the application.
//!
//! It will open the main window and connect default to server or open the connect window.
bool SpringLobbyApp::OnInit()
{
	wxSetEnv( _T("UBUNTU_MENUPROXY"), _T("0") );
    //this triggers the Cli Parser amongst other stuff
    if (!wxApp::OnInit())
		return false;
	SetAppName( m_appname );

    if (!m_crash_handle_disable) {
    #if wxUSE_ON_FATAL_EXCEPTION
        wxHandleFatalExceptions( true );
    #endif
    #if defined(__WXMSW__) && defined(ENABLE_DEBUG_REPORT)
        //this undocumented function acts as a workaround for the dysfunctional
        // wxUSE_ON_FATAL_EXCEPTION on msw when mingw is used (or any other non SEH-capable compiler )
        SetUnhandledExceptionFilter(filter);
    #endif
    }

    //initialize all loggers, we'll use the returned pointer to set correct parent window later
    wxLogChain* logchain = 0;
	wxLogWindow *loggerwin = InitializeLoggingTargets( 0, m_log_console, m_log_file_path, m_log_window_show, !m_crash_handle_disable, m_log_verbosity, logchain );

    //this needs to called _before_ mainwindow instance is created
    wxInitAllImageHandlers();
    wxFileSystem::AddHandler(new wxZipFSHandler);
    wxSocketBase::Initialize();


#ifdef __WXMSW__
    wxString path = wxPathOnly( wxStandardPaths::Get().GetExecutablePath() ) + wxFileName::GetPathSeparator() + _T("locale");
#else
	#if defined(LOCALE_INSTALL_DIR)
		wxString path ( _T(LOCALE_INSTALL_DIR) );
	#else
		// use a dummy name here, we're only interested in the base path
		wxString path = wxStandardPaths::Get().GetLocalizedResourcesDir(_T("noneWH"),wxStandardPaths::ResourceCat_Messages);
		path = path.Left( path.First(_T("noneWH") ) );
	#endif
#endif
    m_translationhelper = new wxTranslationHelper( *( (wxApp*)this ), path );
    m_translationhelper->Load();

	if ( !wxDirExists( GetConfigfileDir() ) )
		wxMkdir( GetConfigfileDir() );

#ifdef __WXMSW__
	sett().SetSearchSpringOnlyInSLPath( sett().GetSearchSpringOnlyInSLPath() );
#endif
	sett().SetSpringBinary( sett().GetCurrentUsedSpringIndex(), sett().GetCurrentUsedSpringBinary() );
	sett().SetUnitSync( sett().GetCurrentUsedSpringIndex(), sett().GetCurrentUsedUnitSync() );

	if ( sett().DoResetPerspectives() )
	{
		//we do this early on and reset the config var a little later so we can save a def. perps once mw is created
		sett().RemoveLayouts();
		sett().SetDoResetPerspectives( false );
		ui().mw().SavePerspectives( _T("SpringLobby-default") );
	}

	sett().RefreshSpringVersionList();

	//this should take off the firstload time considerably *ie nil it :P )
	mapSelectDialog();
	if ( !m_customizer_archive_name.IsEmpty() )
	{//this needsto happen before usync load
		sett().SetForcedSpringConfigFilePath( GetCustomizedEngineConfigFilePath() );
	}
	//unitsync first load, NEEDS to be blocking
	const bool usync_loaded = usync().ReloadUnitSyncLib();
	if ( !sett().IsFirstRun() && !usync_loaded )
	{
		customMessageBox( SL_MAIN_ICON, _("Please check that the file given in Preferences->Spring is a proper, readable unitsync library"),
						 _("Coulnd't load required unitsync library"), wxOK );
	}

	#ifndef DISABLE_SOUND
		//sound sources/buffer init
		sound();
	#endif


	CacheAndSettingsSetup();

	if ( !m_customizer_archive_name.IsEmpty() ) {
		if ( SLcustomizations().Init( m_customizer_archive_name ) ) {
			ui().mw().SetIcons( SLcustomizations().GetAppIconBundle() );
		}
		else {
			customMessageBox( SL_MAIN_ICON, _("Couldn't load customizations for ") + m_customizer_archive_name + _("\nPlease check that that is the correct name, passed in qoutation"), _("Fatal error"), wxOK );
//            wxLogError( _("Couldn't load customizations for ") + m_customizer_archive_name + _("\nPlease check that that is the correct name, passed in qoutation"), _("Fatal error") );
			exit( OnExit() );//for some twisted reason returning false here does not terminate the app
		}
	}

	notificationManager(); //needs to be initialized too
    ui().ShowMainWindow();
    SetTopWindow( &ui().mw() );
	if ( sett().DoResetPerspectives() )
	{
		//now that mainwindow is shown, we can save what is the default layout and remove the flag to reset
		sett().SetDoResetPerspectives( false );
		ui().mw().SavePerspectives( _T("SpringLobby-default") );
	}

	//interim fix for resize crashes on metacity and kwin
	#ifdef __WXMSW__
		mapSelectDialog().Reparent( &ui().mw() );
	#endif

    ui().FirstRunWelcome();
    m_timer->Start( TIMER_INTERVAL );

    ui().mw().SetLogWin( loggerwin, logchain );

#ifndef NO_TORRENT_SYSTEM
    plasmaInterface();
//    plasmaInterface().InitResourceList();
//	plasmaInterface().FetchResourceList();
#endif


    return true;
}
static void DoClickPath(
    PF_InData       *in_data,
    PF_OutData      *out_data,
    PF_ParamDef     *params[],
    PF_LayerDef     *output,
    PF_EventExtra   *event_extra,
    ArbitraryData   *arb_data,
    SequenceData    *seq_data)
{
    ExtensionMap extensions;
    
    for(int i=0; i < OCIO::FileTransform::getNumFormats(); i++)
    {
        const char *extension = OCIO::FileTransform::getFormatExtensionByIndex(i);
        const char *format = OCIO::FileTransform::getFormatNameByIndex(i);
    
        if(extension != std::string("ccc")) // .ccc files require an ID parameter
            extensions[ extension ] = format;
    }
    
    extensions[ "ocio" ] = "OCIO Format";
    

    void *hwndOwner = NULL;

#ifdef WIN_ENV
    PF_GET_PLATFORM_DATA(PF_PlatData_MAIN_WND, &hwndOwner);
#endif

    char c_path[ARB_PATH_LEN + 1] = { '\0' };
    
    bool result = OpenFile(c_path, ARB_PATH_LEN, extensions, hwndOwner);
    
    
    if(result)
    {
        Path path(c_path, GetProjectDir(in_data));
        
        OpenColorIO_AE_Context *new_context = new OpenColorIO_AE_Context(path.full_path(),
                                                                    OCIO_SOURCE_CUSTOM);
        
        if(new_context == NULL)
            throw OCIO::Exception("WTF?");
            
        
        if(seq_data->context)
        {
            delete seq_data->context;
        }
        
        seq_data->context = new_context;
        
        arb_data->source = seq_data->source = OCIO_SOURCE_CUSTOM;
        
        strncpy(arb_data->path, path.full_path().c_str(), ARB_PATH_LEN);
        strncpy(arb_data->relative_path, path.relative_path(false).c_str(), ARB_PATH_LEN);
        
        strncpy(seq_data->path, arb_data->path, ARB_PATH_LEN);
        strncpy(seq_data->relative_path, arb_data->relative_path, ARB_PATH_LEN);
        
        
        // try to retain settings if it looks like the same situation,
        // possibly fixing a moved path
        if(OCIO_ACTION_NONE == arb_data->action ||
            (OCIO_ACTION_LUT == new_context->getAction() && OCIO_ACTION_LUT != arb_data->action) ||
            (OCIO_ACTION_LUT != new_context->getAction() && OCIO_ACTION_LUT == arb_data->action) ||
            (OCIO_ACTION_LUT != new_context->getAction() &&
               (-1 == FindInVec(new_context->getInputs(), arb_data->input) ||
                -1 == FindInVec(new_context->getInputs(), arb_data->output) ||
                -1 == FindInVec(new_context->getTransforms(), arb_data->transform) ||
                -1 == FindInVec(new_context->getDevices(), arb_data->device) ) ) )
        {
            // Configuration is different, so initialize defaults
            arb_data->action = seq_data->context->getAction();
            
            if(arb_data->action == OCIO_ACTION_LUT)
            {
                arb_data->invert = FALSE;
                arb_data->interpolation = OCIO_INTERP_LINEAR;
            }
            else
            {
                strncpy(arb_data->input, seq_data->context->getInput().c_str(), ARB_SPACE_LEN);
                strncpy(arb_data->output, seq_data->context->getOutput().c_str(), ARB_SPACE_LEN);
                strncpy(arb_data->transform, seq_data->context->getTransform().c_str(), ARB_SPACE_LEN);
                strncpy(arb_data->device, seq_data->context->getDevice().c_str(), ARB_SPACE_LEN);
            }
        }
        else
        {
            // Configuration is the same, retain current settings
            if(arb_data->action == OCIO_ACTION_LUT)
            {
                seq_data->context->setupLUT(arb_data->invert, arb_data->interpolation);
            }
            else if(arb_data->action == OCIO_ACTION_CONVERT)
            {
                seq_data->context->setupConvert(arb_data->input, arb_data->output);
            }
            else if(arb_data->action == OCIO_ACTION_DISPLAY)
            {
                seq_data->context->setupDisplay(arb_data->input, arb_data->device, arb_data->transform);
                
                // transform may have changed
                strncpy(arb_data->transform, seq_data->context->getTransform().c_str(), ARB_SPACE_LEN);
            }
        }
        
        params[OCIO_DATA]->uu.change_flags = PF_ChangeFlag_CHANGED_VALUE;
        
        seq_data->status = STATUS_USING_ABSOLUTE;
    }
}
Example #19
0
nglInputDevice* nglInputDeviceLinux::Enum (uint Index)
{
  if (!mInitCalled)
  {
    App->AddExit(Exit);
    mInitCalled = true;
  }

  if (!mpBasePath)
  {
    nglPath path_old(_T("/dev/js1"));
    nglPath path_new(_T("/dev/input/js1"));

    if (path_new.Exists())
      mpBasePath = (nglChar*) _T("/dev/input/js");
    else
    if (path_old.Exists())
      mpBasePath = (nglChar*) _T("/dev/js");
  }

  // No valid path to joystick devices
  if (!mpBasePath)
    return NULL;

  uint i;
  uint valid = 0;
  bool found = false;

  for (i = 0; !found; i++)
  {
    // Check existence of device node '{basepath}/js{i}'
    nglString path_str;
    path_str.Format("%s%d", mpBasePath, i);

    nglPath path(path_str);
    if (!path.Exists())
      break; // No more devices to check, end there

    // Grow vector if necessary
    if (i >= mDeviceList.size())
    {
      mDeviceList.resize(i + 1);
      mDeviceList[i] = NULL;
    }

    // If device has no associated instance, create one now
    if (mDeviceList[i] == NULL)
      mDeviceList[i] = new nglInputDeviceLinux(path);

    if (mDeviceList[i]->IsValid())
      valid++;
    found = (valid == Index + 1);
  }

  if (!found)
    return NULL;

  nglInputDeviceLinux* dev = mDeviceList[i-1];

  return dev ? CreateDevice(dev) : NULL;
}
static void DoClickConfig(
    PF_InData       *in_data,
    PF_OutData      *out_data,
    PF_ParamDef     *params[],
    PF_LayerDef     *output,
    PF_EventExtra   *event_extra,
    ArbitraryData   *arb_data,
    SequenceData    *seq_data)
{
    void *hwndOwner = NULL;

#ifdef WIN_ENV
    PF_GET_PLATFORM_DATA(PF_PlatData_MAIN_WND, &hwndOwner);
#endif

    ConfigVec configs;
    GetStdConfigs(configs);
    
    if(configs.size() == 0)
        configs.push_back("(nada)"); // menu makes a gray entry that says "No configs in $PATH"
    
    
    MenuVec menu_items;
    int selected = 0;
    
    menu_items.push_back("$OCIO"); // menu will gray this out if $OCIO is not defined
    
    menu_items.push_back("(-"); // this tells the menu to make a seperator
    
    for(ConfigVec::const_iterator i = configs.begin(); i != configs.end(); ++i)
    {
        menu_items.push_back( *i );
        
        if(arb_data->source == OCIO_SOURCE_STANDARD && arb_data->path == *i)
        {
            selected = menu_items.size() - 1;
        }
    }
    
    menu_items.push_back("(-");
    
    menu_items.push_back("Custom...");
    
    int custom_choice = menu_items.size() - 1;
    
    if(arb_data->source == OCIO_SOURCE_CUSTOM)
    {
        selected = -1;
    }
    
    
    int choice = PopUpMenu(menu_items, selected, hwndOwner);
    
    
    if(choice == custom_choice)
    {
        // custom is the same as clicking the path
        DoClickPath(in_data, out_data, params, output, event_extra, arb_data, seq_data);
    }
    else if(choice != selected)
    {
        OpenColorIO_AE_Context *new_context = NULL;
        
        if(choice == 0)
        {
            // $OCIO
            char *file = std::getenv("OCIO");
            
            if(file)
            {
                Path path(file, GetProjectDir(in_data));
                
                new_context = new OpenColorIO_AE_Context(path.full_path(),
                                                            OCIO_SOURCE_ENVIRONMENT);
                
                arb_data->source = seq_data->source = OCIO_SOURCE_ENVIRONMENT;
                
                strncpy(arb_data->path, path.full_path().c_str(), ARB_PATH_LEN);
                strncpy(arb_data->relative_path, path.relative_path(false).c_str(), ARB_PATH_LEN);
            }
            else
                throw OCIO::Exception("No $OCIO environment variable defined."); 
        }
        else
        {
            // standard configs
            std::string config = configs[choice - 2];
            
            std::string path = GetStdConfigPath(config);
            
            if( !path.empty() )
            {
                new_context = new OpenColorIO_AE_Context(config, OCIO_SOURCE_STANDARD);
                
                arb_data->source = seq_data->source = OCIO_SOURCE_STANDARD;
                
                strncpy(arb_data->path, config.c_str(), ARB_PATH_LEN);
                strncpy(arb_data->relative_path, path.c_str(), ARB_PATH_LEN);
            }
            else
                throw OCIO::Exception("Problem loading OCIO configuration."); 
        }
        
        
        if(new_context)
        {
            if(seq_data->context)
            {
                delete seq_data->context;
            }
            
            seq_data->context = new_context;
            
            
            strncpy(seq_data->path, arb_data->path, ARB_PATH_LEN);
            strncpy(seq_data->relative_path, arb_data->relative_path, ARB_PATH_LEN);
            
            // try to retain settings if it looks like the same situation,
            // possibly fixing a moved path
            if(OCIO_ACTION_NONE == arb_data->action ||
                (OCIO_ACTION_LUT == new_context->getAction() && OCIO_ACTION_LUT != arb_data->action) ||
                (OCIO_ACTION_LUT != new_context->getAction() && OCIO_ACTION_LUT == arb_data->action) ||
                (OCIO_ACTION_LUT != new_context->getAction() &&
                   (-1 == FindInVec(new_context->getInputs(), arb_data->input) ||
                    -1 == FindInVec(new_context->getInputs(), arb_data->output) ||
                    -1 == FindInVec(new_context->getTransforms(), arb_data->transform) ||
                    -1 == FindInVec(new_context->getDevices(), arb_data->device) ) ) )
            {
                // Configuration is different, so initialize defaults
                arb_data->action = seq_data->context->getAction();
                
                if(arb_data->action == OCIO_ACTION_LUT)
                {
                    arb_data->invert = FALSE;
                    arb_data->interpolation = OCIO_INTERP_LINEAR;
                }
                else
                {
                    strncpy(arb_data->input, seq_data->context->getInput().c_str(), ARB_SPACE_LEN);
                    strncpy(arb_data->output, seq_data->context->getOutput().c_str(), ARB_SPACE_LEN);
                    strncpy(arb_data->transform, seq_data->context->getTransform().c_str(), ARB_SPACE_LEN);
                    strncpy(arb_data->device, seq_data->context->getDevice().c_str(), ARB_SPACE_LEN);
                }
            }
            else
            {
                // Configuration is the same, retain current settings
                if(arb_data->action == OCIO_ACTION_LUT)
                {
                    seq_data->context->setupLUT(arb_data->invert, arb_data->interpolation);
                }
                else if(arb_data->action == OCIO_ACTION_CONVERT)
                {
                    seq_data->context->setupConvert(arb_data->input, arb_data->output);
                }
                else if(arb_data->action == OCIO_ACTION_DISPLAY)
                {
                    seq_data->context->setupDisplay(arb_data->input, arb_data->device, arb_data->transform);
                    
                    // transform may have changed
                    strncpy(arb_data->transform, seq_data->context->getTransform().c_str(), ARB_SPACE_LEN);
                }
            }
            
            params[OCIO_DATA]->uu.change_flags = PF_ChangeFlag_CHANGED_VALUE;
            
            seq_data->status = STATUS_OK;
        }
    }
}
Example #21
0
bool Bundle::parsePlist(const QString &loc)
{
    QFile f(loc);
    if (!f.open(QIODevice::ReadOnly)) {
        qWarning("Couldn't open info file: '%s'", qPrintable(loc));
        return false;
    }

    QMap<QString, QString> infoMap;
    QString str = f.readAll();
    QXmlStreamReader reader(str);
    while (!reader.atEnd()) {
        reader.readNext();
        // do processing
        if (reader.isStartElement()) {
            //qDebug() << reader.name().toString();
            if (reader.name() == "key") {
                QString key, value;
                reader.readNext();
                if (reader.isCharacters()) {
                    QString str = reader.text().toString();
                    str = str.trimmed();
                    if (!str.isEmpty())
                        key = str;
                }
                if (key.isEmpty())
                    continue;
                while (!reader.isStartElement())
                    reader.readNext();
                if (reader.name() != "string" &&
                    reader.name() != "integer") {
                    qDebug()<<"Unrecognized val "<<reader.name().toString()
                            <<" for key "<<key;
                    continue;
                }
                reader.readNext();
                if (reader.isCharacters()) {
                    QString str = reader.text().toString();
                    str = str.trimmed();
                    if (!str.isEmpty())
                        value = str;
                }
                //qDebug()<<"key = "<<key<<", value = "<<value;
                infoMap.insert(key, value);
            }
        }
    }

    QMap<QString, QString>::const_iterator itr;
    for (itr = infoMap.constBegin(); itr != infoMap.constEnd(); ++itr) {
        kDebug() << itr.key() << itr.value();
        if (itr.key() == QLatin1String("CFBundleIdentifier")) {
            m_bundleId = itr.value();
        } else if (itr.key() == QLatin1String("CFBundleName")) {
            m_description = itr.value();
        } else if (itr.key() == QLatin1String("CFBundleDisplayName")) {
            m_name = itr.value();
        } else if (itr.key() == QLatin1String("CFBundleVersion")) {
            m_version = itr.value();
        } else if (itr.key() == QLatin1String("CloseBoxInsetX")) {

        } else if (itr.key() == QLatin1String("CloseBoxInsetY")) {

        } else if (itr.key() == QLatin1String("Height")) {
            m_height = itr.value().toInt();
        } else if (itr.key() == QLatin1String("Width")) {
            m_width = itr.value().toInt();
        } else if (itr.key() == QLatin1String("MainHTML")) {
            m_htmlLocation = QString("%1%2").arg(path()).arg(itr.value());
            addFileDefinition("mainscript", itr.value(), i18n("Main Webpage"));
        } else {
            qDebug()<<"Unrecognized key = "<<itr.key();
        }
    }
    m_iconLocation = QString("%1Icon.png").arg(path());
    kDebug() << path();
    addDirectoryDefinition("root", "/", i18n("Root HTML directory"));

    //qDebug()<<"name = "<<m_name;
    //qDebug()<<"id   = "<<m_bundleId;
    //qDebug()<<"html = "<<m_htmlLocation;
    //qDebug()<<"icon = "<<m_iconLocation;

    return !m_bundleId.isEmpty();
}
/**
 * \brief
 */
bool NewClassDlg::ValidateInput()
{
    // validate the class name
    if(!IsValidCppIndetifier(m_textClassName->GetValue())) {
        wxString msg;
        msg << wxT("'") << m_textClassName->GetValue() << _("' is not a valid C++ qualifier");
        wxMessageBox(msg, _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }

    // validate the namespace
    if(!m_textCtrlNamespace->GetValue().IsEmpty()) {
        wxArrayString namespacesList;
        this->GetNamespacesList(namespacesList);
        // validate each namespace
        for(unsigned int i = 0; i < namespacesList.Count(); i++) {
            if(!IsValidCppIndetifier(namespacesList[i])) {
                wxString msg;
                msg << wxT("'") << namespacesList[i] << _("' is not a valid C++ qualifier");
                wxMessageBox(msg, _("CodeLite"), wxOK | wxICON_WARNING);
                return false;
            }
        }
    }

    // validate the path of the class
    wxString path(m_textCtrlGenFilePath->GetValue());
    if(!wxDir::Exists(path)) {
        wxString msg;
        msg << wxT("'") << path << _("': directory does not exist");
        wxMessageBox(msg, _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }

    if(GetClassFile().IsEmpty()) {
        wxMessageBox(_("Empty file name"), _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }

    wxString cpp_file;
    cpp_file << GetClassPath() << wxFileName::GetPathSeparator() << GetClassFile() << wxT(".cpp");
    if(wxFileName::FileExists(cpp_file)) {
        if(wxMessageBox(
               wxString::Format(_("A file with this name: '%s' already exists, continue anyway?"), cpp_file.GetData()),
               _("CodeLite"),
               wxYES_NO | wxICON_WARNING) == wxNO) {
            return false;
        }
    }
    wxString h_file;
    h_file << GetClassPath() << wxFileName::GetPathSeparator() << GetClassFile() << wxT(".h");
    if(wxFileName::FileExists(h_file)) {
        if(wxMessageBox(
               wxString::Format(_("A file with this name: '%s' already exists, continue anyway?"), h_file.GetData()),
               _("CodeLite"),
               wxYES_NO | wxICON_WARNING) == wxNO) {
            return false;
        }
    }

    if(GetVirtualDirectoryPath().IsEmpty()) {
        wxMessageBox(_("Please select a virtual directory"), _("CodeLite"), wxOK | wxICON_WARNING);
        return false;
    }
    return true;
}
/**
 * Downloads datafiles from the archives, and saves to the users save default
 * directory.
 * @param URL :: The URL of the file to download.
 * @param fileName :: The name of the file to save to disk.
 * @return The full path to the saved file.
 */
std::string CatalogDownloadDataFiles::doDownloadandSavetoLocalDrive(
    const std::string &URL, const std::string &fileName) {
  std::string pathToDownloadedDatafile;

  try {
    Poco::URI uri(URL);

    std::string path(uri.getPathAndQuery());
    clock_t start = clock();

    Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> certificateHandler =
        new Poco::Net::AcceptCertificateHandler(true);
    // Currently do not use any means of authentication. This should be updated
    // IDS has signed certificate.
    const Poco::Net::Context::Ptr context =
        new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "",
                               Poco::Net::Context::VERIFY_NONE);
    // Create a singleton for holding the default context. E.g. any future
    // requests to publish are made to this certificate and context.
    Poco::Net::SSLManager::instance().initializeClient(
        nullptr, certificateHandler, context);

    // Session takes ownership of socket
    Poco::Net::SecureStreamSocket *socket =
        new Poco::Net::SecureStreamSocket(context);
    Poco::Net::HTTPSClientSession session(*socket);
    socket = nullptr;
    session.setHost(uri.getHost());
    session.setPort(uri.getPort());

    Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path,
                                   Poco::Net::HTTPMessage::HTTP_1_1);
    session.sendRequest(request);

    // Close the request by requesting a response.
    Poco::Net::HTTPResponse response;
    // Store the response for use IF an error occurs (e.g. 404).
    std::istream &responseStream = session.receiveResponse(response);

    // Obtain the status returned by the server to verify if it was a success.
    Poco::Net::HTTPResponse::HTTPStatus HTTPStatus = response.getStatus();
    // The error message returned by the IDS (if one exists).
    std::string IDSError =
        CatalogAlgorithmHelper().getIDSError(HTTPStatus, responseStream);
    // Cancel the algorithm and display the message if it exists.
    if (!IDSError.empty()) {
      // As an error occurred we must cancel the algorithm to prevent success
      // message.
      this->cancel();
      // Output an appropriate error message from the JSON object returned by
      // the IDS.
      g_log.error(IDSError);
      return "";
    }

    // Save the file to local disk if no errors occurred on the IDS.
    pathToDownloadedDatafile = saveFiletoDisk(responseStream, fileName);

    clock_t end = clock();
    float diff = float(end - start) / CLOCKS_PER_SEC;
    g_log.information() << "Time taken to download file " << fileName << " is "
                        << std::fixed << std::setprecision(2) << diff
                        << " seconds\n";

  } catch (Poco::Net::SSLException &error) {
    throw std::runtime_error(error.displayText());
  }
  // A strange error occurs (what returns: {I/O error}, while message returns: {
  // 9: The BIO reported an error }.
  // This bug has been fixed in POCO 1.4 and is noted -
  // http://sourceforge.net/p/poco/bugs/403/
  // I have opted to catch the exception and do nothing as this allows the
  // load/download functionality to work.
  // However, the port the user used to download the file will be left open.
  //
  // In addition, there's a crash when destructing SecureSocketImpl (internal to
  // SecureSocketStream, which is
  // created and destroyed by HTTPSClientSession). We avoid that crash by
  // instantiating SecureSocketStream
  // ourselves and passing it to the HTTPSClientSession, which takes ownership.
  catch (Poco::Exception &error) {
    throw std::runtime_error(error.displayText());
  }

  return pathToDownloadedDatafile;
}
Example #24
0
 void InMatchExpression::copyTo( InMatchExpression* toFillIn ) const {
     toFillIn->init( path() );
     _arrayEntries.copyTo( toFillIn->_arrayEntries );
 }
Example #25
0
void
PathBox::MessageReceived(BMessage *msg)
{
	switch(msg->what) {
		case M_ENTRY_CHOSEN: {
			entry_ref ref;
			if (msg->FindRef("refs",&ref) == B_OK) {
				BPath path(&ref);
				fPathControl->SetText(path.Path());
			}
			break;
		}
		case M_SHOW_FILEPANEL: {
			if (!fFilePanel->IsShowing())
				fFilePanel->Show();
			break;
		}
		case M_PATHBOX_CHANGED: {
			if (IsValidating()) {
				if (strlen(fPathControl->Text()) < 1)
					break;
				
				BEntry entry(fPathControl->Text());
				if (entry.InitCheck() != B_OK
					|| !entry.Exists()) {
					BAlert *alert = new BAlert("", "The location entered does not exist."
												" Please check to make sure you have"
												" entered it correctly.",
												"OK");
					alert->Go();
					fPathControl->MakeFocus();
				}
			}
			break;
		}
		case B_SET_PROPERTY:
		case B_GET_PROPERTY: {
			BMessage reply(B_REPLY);
			bool handled = false;
	
			BMessage specifier;
			int32 index;
			int32 form;
			const char *property;
			if (msg->GetCurrentSpecifier(&index, &specifier, &form, &property) == B_OK) {
				if (strcmp(property, "Value") == 0) {
					if (msg->what == B_GET_PROPERTY) {
						reply.AddString("result", fPathControl->Text());
						handled = true;
					} else {
						// B_GET_PROPERTY
						BString value;
						if (msg->FindString("data", &value) == B_OK) {
							SetPath(value.String());
							reply.AddInt32("error", B_OK);
							handled = true;
						}
					}
				} else if (strcmp(property, "Enabled") == 0) {
					if (msg->what == B_GET_PROPERTY) {
						reply.AddBool("result", IsEnabled());
						handled = true;
					} else {
						// B_GET_PROPERTY
						bool enabled;
						if (msg->FindBool("data", &enabled) == B_OK) {
							SetEnabled(enabled);
							reply.AddInt32("error", B_OK);
							handled = true;
						}
					}
				}
			}
			
			if (handled) {
				msg->SendReply(&reply);
				return;
			}
			break;
		}
		default: {
			BView::MessageReceived(msg);
			break;
		}
	}
}
Example #26
0
status_t
DesktopSettingsPrivate::_Load()
{
	// TODO: add support for old app_server_settings file as well

	BPath basePath;
	status_t status = _GetPath(basePath);
	if (status < B_OK)
		return status;

	// read workspaces settings

	BPath path(basePath);
	path.Append("workspaces");

	BFile file;
	status = file.SetTo(path.Path(), B_READ_ONLY);
	if (status == B_OK) {
		BMessage settings;
		status = settings.Unflatten(&file);
		if (status == B_OK) {
			int32 columns;
			int32 rows;
			if (settings.FindInt32("columns", &columns) == B_OK
				&& settings.FindInt32("rows", &rows) == B_OK) {
				_ValidateWorkspacesLayout(columns, rows);
				fWorkspacesColumns = columns;
				fWorkspacesRows = rows;
			}

			int32 i = 0;
			while (i < kMaxWorkspaces && settings.FindMessage("workspace",
					i, &fWorkspaceMessages[i]) == B_OK) {
				i++;
			}
		}
	}

	// read font settings

	path = basePath;
	path.Append("fonts");

	status = file.SetTo(path.Path(), B_READ_ONLY);
	if (status == B_OK) {
		BMessage settings;
		status = settings.Unflatten(&file);
		if (status == B_OK && gFontManager->Lock()) {
			const char* family;
			const char* style;
			float size;

			if (settings.FindString("plain family", &family) == B_OK
				&& settings.FindString("plain style", &style) == B_OK
				&& settings.FindFloat("plain size", &size) == B_OK) {
				FontStyle* fontStyle = gFontManager->GetStyle(family, style);
				fPlainFont.SetStyle(fontStyle);
				fPlainFont.SetSize(size);
			}

			if (settings.FindString("bold family", &family) == B_OK
				&& settings.FindString("bold style", &style) == B_OK
				&& settings.FindFloat("bold size", &size) == B_OK) {
				FontStyle* fontStyle = gFontManager->GetStyle(family, style);
				fBoldFont.SetStyle(fontStyle);
				fBoldFont.SetSize(size);
			}

			if (settings.FindString("fixed family", &family) == B_OK
				&& settings.FindString("fixed style", &style) == B_OK
				&& settings.FindFloat("fixed size", &size) == B_OK) {
				FontStyle* fontStyle = gFontManager->GetStyle(family, style);
				if (fontStyle != NULL && fontStyle->IsFixedWidth())
					fFixedFont.SetStyle(fontStyle);
				fFixedFont.SetSize(size);
			}

			int32 hinting;
			if (settings.FindInt32("hinting", &hinting) == B_OK)
				gDefaultHintingMode = hinting;

			gFontManager->Unlock();
		}
	}

	// read mouse settings

	path = basePath;
	path.Append("mouse");

	status = file.SetTo(path.Path(), B_READ_ONLY);
	if (status == B_OK) {
		BMessage settings;
		status = settings.Unflatten(&file);
		if (status == B_OK) {
			int32 mode;
			if (settings.FindInt32("mode", &mode) == B_OK)
				fMouseMode = (mode_mouse)mode;

			int32 focusFollowsMouseMode;
			if (settings.FindInt32("focus follows mouse mode",
					&focusFollowsMouseMode) == B_OK) {
				fFocusFollowsMouseMode
					= (mode_focus_follows_mouse)focusFollowsMouseMode;
			}

			bool acceptFirstClick;
			if (settings.FindBool("accept first click", &acceptFirstClick)
					== B_OK) {
				fAcceptFirstClick = acceptFirstClick;
			}
		}
	}

	// read appearance settings

	path = basePath;
	path.Append("appearance");

	status = file.SetTo(path.Path(), B_READ_ONLY);
	if (status == B_OK) {
		BMessage settings;
		status = settings.Unflatten(&file);
		if (status == B_OK) {
			float fontSize;
			if (settings.FindFloat("font size", &fontSize) == B_OK)
				fMenuInfo.font_size = fontSize;

			const char* fontFamily;
			if (settings.FindString("font family", &fontFamily) == B_OK)
				strlcpy(fMenuInfo.f_family, fontFamily, B_FONT_FAMILY_LENGTH);

			const char* fontStyle;
			if (settings.FindString("font style", &fontStyle) == B_OK)
				strlcpy(fMenuInfo.f_style, fontStyle, B_FONT_STYLE_LENGTH);

			rgb_color bgColor;
			if (settings.FindInt32("bg color", (int32*)&bgColor) == B_OK)
				fMenuInfo.background_color = bgColor;

			int32 separator;
			if (settings.FindInt32("separator", &separator) == B_OK)
				fMenuInfo.separator = separator;

			bool clickToOpen;
			if (settings.FindBool("click to open", &clickToOpen) == B_OK)
				fMenuInfo.click_to_open = clickToOpen;

			bool triggersAlwaysShown;
			if (settings.FindBool("triggers always shown", &triggersAlwaysShown)
					 == B_OK) {
				fMenuInfo.triggers_always_shown = triggersAlwaysShown;
			}

			bool subpix;
			if (settings.FindBool("subpixel antialiasing", &subpix) == B_OK)
				gSubpixelAntialiasing = subpix;

			int8 averageWeight;
			if (settings.FindInt8("subpixel average weight", &averageWeight)
					== B_OK) {
				gSubpixelAverageWeight = averageWeight;
			}

			bool subpixelOrdering;
			if (settings.FindBool("subpixel ordering", &subpixelOrdering)
					== B_OK) {
				gSubpixelOrderingRGB = subpixelOrdering;
			}

			for (int32 i = 0; i < kNumColors; i++) {
				char colorName[12];
				snprintf(colorName, sizeof(colorName), "color%ld",
					(int32)index_to_color_which(i));

				settings.FindInt32(colorName, (int32*)&fShared.colors[i]);
			}
		}
	}

	// read dragger settings

	path = basePath;
	path.Append("dragger");

	status = file.SetTo(path.Path(), B_READ_ONLY);
	if (status == B_OK) {
		BMessage settings;
		status = settings.Unflatten(&file);
		if (status == B_OK) {
			if (settings.FindBool("show", &fShowAllDraggers) != B_OK)
				fShowAllDraggers = true;
		}
	}

	return B_OK;
}
Example #27
0
bool WDTFile::init(char *map_id, unsigned int mapID)
{
    if (WDT.isEof())
    {
        //printf("Can't find WDT file.\n");
        return false;
    }

    char fourcc[5];
    uint32 size;

    std::string dirname = std::string(szWorkDirWmo) + "/dir_bin";
    FILE *dirfile;
    dirfile = fopen(dirname.c_str(), "ab");
    if(!dirfile)
    {
        printf("Can't open dirfile!'%s'\n", dirname.c_str());
        return false;
    }

    while (!WDT.isEof())
    {
        WDT.read(fourcc,4);
        WDT.read(&size, 4);

        flipcc(fourcc);
        fourcc[4] = 0;

        size_t nextpos = WDT.getPos() + size;

        if (!strcmp(fourcc,"MAIN"))
        {
        }
        if (!strcmp(fourcc,"MWMO"))
        {
            // global map objects
            if (size)
            {
                char *buf = new char[size];
                WDT.read(buf, size);
                char *p=buf;
                int q = 0;
                gWmoInstansName = new string[size];
                while (p<buf+size)
                {
                    string path(p);
                    char* s=wdtGetPlainName(p);
                    fixnamen(s,strlen(s));
                    p=p+strlen(p)+1;
                    gWmoInstansName[q++] = s;
                }
                delete[] buf;
            }
        }
        else if (!strcmp(fourcc,"MODF"))
        {
            // global wmo instance data
            if (size)
            {
                gnWMO = (int)size / 64;
                string gWMO_mapname;
                string fake_mapname;
                fake_mapname = "65 65 ";
                //gWMO_mapname = fake_mapname + filename;
                gWMO_mapname = fake_mapname + std::string(map_id);
                for (int i=0; i<gnWMO; ++i)
                {
                    int id;
                    WDT.read(&id, 4);
                    WMOInstance inst(WDT,gWmoInstansName[id].c_str(),mapID, 65, 65, dirfile);
                }
                delete[] gWmoInstansName;
            }
        }
        WDT.seek((int)nextpos);
    }

    WDT.close();
    fclose(dirfile);
    return true;
}
Example #28
0
status_t
DesktopSettingsPrivate::Save(uint32 mask)
{
#if TEST_MODE
	return B_OK;
#endif

	BPath basePath;
	status_t status = _GetPath(basePath);
	if (status != B_OK)
		return status;

	if (mask & kWorkspacesSettings) {
		BPath path(basePath);
		if (path.Append("workspaces") == B_OK) {
			BMessage settings('asws');
			settings.AddInt32("columns", fWorkspacesColumns);
			settings.AddInt32("rows", fWorkspacesRows);

			for (int32 i = 0; i < kMaxWorkspaces; i++) {
				settings.AddMessage("workspace", &fWorkspaceMessages[i]);
			}

			BFile file;
			status = file.SetTo(path.Path(), B_CREATE_FILE | B_ERASE_FILE
				| B_READ_WRITE);
			if (status == B_OK) {
				status = settings.Flatten(&file, NULL);
			}
		}
	}

	if (mask & kFontSettings) {
		BPath path(basePath);
		if (path.Append("fonts") == B_OK) {
			BMessage settings('asfn');

			settings.AddString("plain family", fPlainFont.Family());
			settings.AddString("plain style", fPlainFont.Style());
			settings.AddFloat("plain size", fPlainFont.Size());

			settings.AddString("bold family", fBoldFont.Family());
			settings.AddString("bold style", fBoldFont.Style());
			settings.AddFloat("bold size", fBoldFont.Size());

			settings.AddString("fixed family", fFixedFont.Family());
			settings.AddString("fixed style", fFixedFont.Style());
			settings.AddFloat("fixed size", fFixedFont.Size());

			settings.AddInt32("hinting", gDefaultHintingMode);

			BFile file;
			status = file.SetTo(path.Path(), B_CREATE_FILE | B_ERASE_FILE
				| B_READ_WRITE);
			if (status == B_OK) {
				status = settings.Flatten(&file, NULL);
			}
		}
	}

	if (mask & kMouseSettings) {
		BPath path(basePath);
		if (path.Append("mouse") == B_OK) {
			BMessage settings('asms');
			settings.AddInt32("mode", (int32)fMouseMode);
			settings.AddInt32("focus follows mouse mode",
				(int32)fFocusFollowsMouseMode);
			settings.AddBool("accept first click", fAcceptFirstClick);

			BFile file;
			status = file.SetTo(path.Path(), B_CREATE_FILE | B_ERASE_FILE
				| B_READ_WRITE);
			if (status == B_OK) {
				status = settings.Flatten(&file, NULL);
			}
		}
	}

	if (mask & kDraggerSettings) {
		BPath path(basePath);
		if (path.Append("dragger") == B_OK) {
			BMessage settings('asdg');
			settings.AddBool("show", fShowAllDraggers);

			BFile file;
			status = file.SetTo(path.Path(), B_CREATE_FILE | B_ERASE_FILE
				| B_READ_WRITE);
			if (status == B_OK) {
				status = settings.Flatten(&file, NULL);
			}
		}
	}

	if (mask & kAppearanceSettings) {
		BPath path(basePath);
		if (path.Append("appearance") == B_OK) {
			BMessage settings('aslk');
			settings.AddFloat("font size", fMenuInfo.font_size);
			settings.AddString("font family", fMenuInfo.f_family);
			settings.AddString("font style", fMenuInfo.f_style);
			settings.AddInt32("bg color",
				(const int32&)fMenuInfo.background_color);
			settings.AddInt32("separator", fMenuInfo.separator);
			settings.AddBool("click to open", fMenuInfo.click_to_open);
			settings.AddBool("triggers always shown",
				fMenuInfo.triggers_always_shown);

			settings.AddBool("subpixel antialiasing", gSubpixelAntialiasing);
			settings.AddInt8("subpixel average weight", gSubpixelAverageWeight);
			settings.AddBool("subpixel ordering", gSubpixelOrderingRGB);

			for (int32 i = 0; i < kNumColors; i++) {
				char colorName[12];
				snprintf(colorName, sizeof(colorName), "color%ld",
					(int32)index_to_color_which(i));
				settings.AddInt32(colorName, (const int32&)fShared.colors[i]);
			}

			BFile file;
			status = file.SetTo(path.Path(), B_CREATE_FILE | B_ERASE_FILE
				| B_READ_WRITE);
			if (status == B_OK) {
				status = settings.Flatten(&file, NULL);
			}
		}
	}

	return status;
}
Example #29
0
void TemporaryFile::keepUntilExit()
{
	_keep = true;
	registerForDeletion(path());
}
Example #30
0
bool TabPage::canUp() {
  return (path() != NULL && fm_path_get_parent(path()) != NULL);
}