コード例 #1
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 gcc_pure
 bool IsAbsolute() const {
   return Path(*this).IsAbsolute();
 }
コード例 #2
0
ファイル: FileZillaIntf.cpp プロジェクト: anyue100/winscp
//---------------------------------------------------------------------------
bool __fastcall TFileZillaIntf::MakeDir(const wchar_t* APath)
{
  DebugAssert(FFileZillaApi != NULL);
  CServerPath Path(APath);
  return Check(FFileZillaApi->MakeDir(Path), L"makedir");
}
コード例 #3
0
ファイル: FileZillaIntf.cpp プロジェクト: anyue100/winscp
//---------------------------------------------------------------------------
bool __fastcall TFileZillaIntf::ListFile(const wchar_t * FileName, const wchar_t * APath)
{
  DebugAssert(FFileZillaApi != NULL);
  CServerPath Path(APath);
  return Check(FFileZillaApi->ListFile(FileName, Path), L"listfile");
}
コード例 #4
0
ファイル: System.cpp プロジェクト: septag/stcore
Path System::GetUserDir()
{
    struct passwd* pw = getpwuid(getuid());
    return Path(pw->pw_dir);
}
コード例 #5
0
ファイル: animation_cache.cpp プロジェクト: Paulloz/godot
void AnimationCache::_update_cache() {

	cache_valid = false;

	ERR_FAIL_COND(!root);
	ERR_FAIL_COND(!root->is_inside_tree());
	ERR_FAIL_COND(animation.is_null());

	for (int i = 0; i < animation->get_track_count(); i++) {

		NodePath np = animation->track_get_path(i);

		Node *node = root->get_node(np);
		if (!node) {

			path_cache.push_back(Path());
			ERR_EXPLAIN("Invalid Track Path in Animation: " + np);
			ERR_CONTINUE(!node);
		}

		Path path;

		Ref<Resource> res;

		if (animation->track_get_type(i) == Animation::TYPE_TRANSFORM) {

			if (np.get_subname_count() > 1) {
				path_cache.push_back(Path());
				ERR_EXPLAIN("Transform tracks can't have a subpath: " + np);
				ERR_CONTINUE(animation->track_get_type(i) == Animation::TYPE_TRANSFORM);
			}

			Spatial *sp = Object::cast_to<Spatial>(node);

			if (!sp) {

				path_cache.push_back(Path());
				ERR_EXPLAIN("Transform track not of type Spatial: " + np);
				ERR_CONTINUE(!sp);
			}

			if (np.get_subname_count() == 1) {
				StringName property = np.get_subname(0);
				String ps = property;

				Skeleton *sk = Object::cast_to<Skeleton>(node);
				if (!sk) {

					path_cache.push_back(Path());
					ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton!: " + np);
					ERR_CONTINUE(!sk);
				}

				int idx = sk->find_bone(ps);
				if (idx == -1) {
					path_cache.push_back(Path());
					ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton Bone!: " + np);
					ERR_CONTINUE(idx == -1);
				}

				path.bone_idx = idx;
				path.skeleton = sk;
			}

			path.spatial = sp;

		} else {
			if (np.get_subname_count() > 0) {

				RES res2;
				Vector<StringName> leftover_subpath;

				// We don't want to cache the last resource unless it is a method call
				bool is_method = animation->track_get_type(i) == Animation::TYPE_METHOD;
				root->get_node_and_resource(np, res2, leftover_subpath, is_method);

				if (res2.is_valid()) {
					path.resource = res2;
				} else {
					path.node = node;
				}
				path.object = res2.is_valid() ? res2.ptr() : (Object *)node;
				path.subpath = leftover_subpath;

			} else {

				path.node = node;
				path.object = node;
				path.subpath = np.get_subnames();
			}
		}

		if (animation->track_get_type(i) == Animation::TYPE_VALUE) {

			if (np.get_subname_count() == 0) {

				path_cache.push_back(Path());
				ERR_EXPLAIN("Value Track lacks property: " + np);
				ERR_CONTINUE(np.get_subname_count() == 0);
			}

		} else if (animation->track_get_type(i) == Animation::TYPE_METHOD) {

			if (path.subpath.size() != 0) { // Trying to call a method of a non-resource

				path_cache.push_back(Path());
				ERR_EXPLAIN("Method Track has property: " + np);
				ERR_CONTINUE(path.subpath.size() != 0);
			}
		}

		path.valid = true;

		path_cache.push_back(path);

		if (!connected_nodes.has(path.node)) {
			connected_nodes.insert(path.node);
			path.node->connect("tree_exiting", this, "_node_exit_tree", Node::make_binds(path.node), CONNECT_ONESHOT);
		}
	}

	cache_dirty = false;
	cache_valid = true;
}
コード例 #6
0
ファイル: Startup.cpp プロジェクト: nkgautam/XCSoar
/**
 * "Boots" up XCSoar
 * @param hInstance Instance handle
 * @param lpCmdLine Command line string
 * @return True if bootup successful, False otherwise
 */
bool
Startup()
{
  VerboseOperationEnvironment operation;

#ifdef HAVE_DOWNLOAD_MANAGER
  Net::DownloadManager::Initialise();
#endif

  LogFormat("Display dpi=%u,%u", Display::GetXDPI(), Display::GetYDPI());

  // Creates the main window

  TopWindowStyle style;
  if (CommandLine::full_screen)
    style.FullScreen();

  style.Resizable();

  MainWindow *const main_window = CommonInterface::main_window =
    new MainWindow();
  main_window->Create(SystemWindowSize(), style);
  if (!main_window->IsDefined())
    return false;

#ifdef ENABLE_OPENGL
  LogFormat("OpenGL: "
#ifdef ANDROID
#ifdef USE_EGL
            "egl=native "
#else
            "egl=no "
#endif
#endif
#ifdef HAVE_OES_DRAW_TEXTURE
            "oesdt=%d "
#endif
#ifdef HAVE_DYNAMIC_MULTI_DRAW_ARRAYS
            "mda=%d "
#endif
            "npot=%d vbo=%d fbo=%d stencil=%#x",
#ifdef HAVE_OES_DRAW_TEXTURE
            OpenGL::oes_draw_texture,
#endif
#ifdef HAVE_DYNAMIC_MULTI_DRAW_ARRAYS
            GLExt::HaveMultiDrawElements(),
#endif
             OpenGL::texture_non_power_of_two,
             OpenGL::vertex_buffer_object,
            OpenGL::frame_buffer_object,
            OpenGL::render_buffer_stencil);
#endif

  CommonInterface::SetUISettings().SetDefaults();
  main_window->Initialise();

#ifdef SIMULATOR_AVAILABLE
  // prompt for simulator if not set by command line argument "-simulator" or "-fly"
  if (!sim_set_in_cmd_line_flag) {
    SimulatorPromptResult result = dlgSimulatorPromptShowModal();
    switch (result) {
    case SPR_QUIT:
      return false;

    case SPR_FLY:
      global_simulator_flag = false;
      break;

    case SPR_SIMULATOR:
      global_simulator_flag = true;
      break;
    }
  }
#endif

  CommonInterface::SetSystemSettings().SetDefaults();
  CommonInterface::SetComputerSettings().SetDefaults();
  CommonInterface::SetUIState().Clear();

  const auto &computer_settings = CommonInterface::GetComputerSettings();
  const auto &ui_settings = CommonInterface::GetUISettings();
  auto &live_blackboard = CommonInterface::GetLiveBlackboard();

  if (!LoadProfile())
    return false;

  operation.SetText(_("Initialising"));

  /* create XCSoarData on the first start */
  CreateDataPath();

  Display::LoadOrientation(operation);
  main_window->CheckResize();

  main_window->InitialiseConfigured();

  {
    file_cache = new FileCache(LocalPath(_T("cache")));
  }

  ReadLanguageFile();

  InputEvents::readFile();

  // Initialize DeviceBlackboard
  device_blackboard = new DeviceBlackboard();
  devices = new MultipleDevices();
  device_blackboard->SetDevices(*devices);

  // Initialize main blackboard data
  task_events = new GlideComputerTaskEvents();
  task_manager = new TaskManager(computer_settings.task, way_points);
  task_manager->SetTaskEvents(*task_events);
  task_manager->Reset();

  protected_task_manager =
    new ProtectedTaskManager(*task_manager, computer_settings.task);

  // Read the terrain file
  operation.SetText(_("Loading Terrain File..."));
  LogFormat("OpenTerrain");
  terrain = RasterTerrain::OpenTerrain(file_cache, operation);

  logger = new Logger();

  glide_computer = new GlideComputer(way_points, airspace_database,
                                     *protected_task_manager,
                                     *task_events);
  glide_computer->ReadComputerSettings(computer_settings);
  glide_computer->SetTerrain(terrain);
  glide_computer->SetLogger(logger);
  glide_computer->Initialise();

  replay = new Replay(logger, *protected_task_manager);

#ifdef HAVE_CMDLINE_REPLAY
  if (CommandLine::replay_path != nullptr) {
    Error error;
    if (!replay->Start(Path(CommandLine::replay_path), error))
      LogError(error);
  }
#endif


  GlidePolar &gp = CommonInterface::SetComputerSettings().polar.glide_polar_task;
  gp = GlidePolar(fixed(0));
  gp.SetMC(computer_settings.task.safety_mc);
  gp.SetBugs(computer_settings.polar.degradation_factor);
  PlaneGlue::FromProfile(CommonInterface::SetComputerSettings().plane,
                         Profile::map);
  PlaneGlue::Synchronize(computer_settings.plane,
                         CommonInterface::SetComputerSettings(), gp);
  task_manager->SetGlidePolar(gp);

  // Read the topography file(s)
  topography = new TopographyStore();
  LoadConfiguredTopography(*topography, operation);

  // Read the waypoint files
  WaypointGlue::LoadWaypoints(way_points, terrain, operation);

  // Read and parse the airfield info file
  WaypointDetails::ReadFileFromProfile(way_points, operation);

  // Set the home waypoint
  WaypointGlue::SetHome(way_points, terrain,
                        CommonInterface::SetComputerSettings().poi,
                        CommonInterface::SetComputerSettings().team_code,
                        device_blackboard, false);

  // ReSynchronise the blackboards here since SetHome touches them
  device_blackboard->Merge();
  CommonInterface::ReadBlackboardBasic(device_blackboard->Basic());

  // Scan for weather forecast
  LogFormat("RASP load");
  rasp = new RaspStore();
  rasp->ScanAll();

  // Reads the airspace files
  ReadAirspace(airspace_database, terrain, computer_settings.pressure,
               operation);

  {
    const AircraftState aircraft_state =
      ToAircraftState(device_blackboard->Basic(),
                      device_blackboard->Calculated());
    ProtectedAirspaceWarningManager::ExclusiveLease lease(glide_computer->GetAirspaceWarnings());
    lease->Reset(aircraft_state);
  }

#ifdef HAVE_NOAA
  noaa_store = new NOAAStore();
  noaa_store->LoadFromProfile();
#endif

  AudioVarioGlue::Initialise();
  AudioVarioGlue::Configure(ui_settings.sound.vario);

  // Start the device thread(s)
  operation.SetText(_("Starting devices"));
  devStartup();

/*
  -- Reset polar in case devices need the data
  GlidePolar::UpdatePolar(true, computer_settings);

  This should be done inside devStartup if it is really required
*/

  operation.SetText(_("Initialising display"));

  GlueMapWindow *map_window = main_window->GetMap();
  if (map_window != nullptr) {
    map_window->SetWaypoints(&way_points);
    map_window->SetTask(protected_task_manager);
    map_window->SetRoutePlanner(&glide_computer->GetProtectedRoutePlanner());
    map_window->SetGlideComputer(glide_computer);
    map_window->SetAirspaces(&airspace_database);

    map_window->SetTopography(topography);
    map_window->SetTerrain(terrain);
    map_window->SetWeather(rasp);

#ifdef HAVE_NOAA
    map_window->SetNOAAStore(noaa_store);
#endif

    /* show map at home waypoint until GPS fix becomes available */
    if (computer_settings.poi.home_location_available)
      map_window->SetLocation(computer_settings.poi.home_location);
  }

  // Finally ready to go.. all structures must be present before this.

  // Create the drawing thread
#ifndef ENABLE_OPENGL
  draw_thread = new DrawThread(*map_window);
  draw_thread->Start(true);
#endif

  // Show the infoboxes
  InfoBoxManager::Show();

  // Create the calculation thread
  CreateCalculationThread();

  // Find unique ID of this PDA
  ReadAssetNumber();

  glide_computer_events = new GlideComputerEvents();
  glide_computer_events->Reset();
  live_blackboard.AddListener(*glide_computer_events);

  all_monitors = new AllMonitors();

  if (!is_simulator() && computer_settings.logger.enable_flight_logger) {
    flight_logger = new GlueFlightLogger(live_blackboard);
    flight_logger->SetPath(LocalPath(_T("flights.log")));
  }

  if (computer_settings.logger.enable_nmea_logger)
    NMEALogger::enabled = true;

  LogFormat("ProgramStarted");

  // Give focus to the map
  main_window->SetDefaultFocus();

  // Start calculation thread
  merge_thread->Start();
  calculation_thread->Start();

  PageActions::Update();

#ifdef HAVE_TRACKING
  tracking = new TrackingGlue();
  tracking->SetSettings(computer_settings.tracking);

#ifdef HAVE_SKYLINES_TRACKING_HANDLER
  if (map_window != nullptr)
    map_window->SetSkyLinesData(&tracking->GetSkyLinesData());
#endif
#endif

  assert(!global_running);
  global_running = true;

  AfterStartup();

  operation.Hide();

  main_window->FinishStartup();

  return true;
}
コード例 #7
0
ファイル: HdmvClipInfo.cpp プロジェクト: JanWillem32/mpc-hc
HRESULT CHdmvClipInfo::ReadPlaylist(CString strPlaylistFile, REFERENCE_TIME& rtDuration, CAtlList<PlaylistItem>& Playlist)
{
    CPath Path(strPlaylistFile);
    rtDuration = 0;

    // Get BDMV folder
    Path.RemoveFileSpec();
    Path.RemoveFileSpec();

    m_hFile = CreateFile(strPlaylistFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
                         OPEN_EXISTING, FILE_ATTRIBUTE_READONLY | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);

    if (m_hFile != INVALID_HANDLE_VALUE) {
        BYTE Buff[100];
        bool bDuplicate = false;
        ReadBuffer(Buff, 4);
        if (memcmp(Buff, "MPLS", 4)) {
            return CloseFile(VFW_E_INVALID_FILE_FORMAT);
        }

        ReadBuffer(Buff, 4);
        if ((memcmp(Buff, "0200", 4) != 0) && (memcmp(Buff, "0100", 4) != 0)) {
            return CloseFile(VFW_E_INVALID_FILE_FORMAT);
        }

        LARGE_INTEGER Pos;
        unsigned short nPlaylistItems;

        Pos.QuadPart = ReadDword(); // PlayList_start_address
        ReadDword();                // PlayListMark_start_address

        // PlayList()
        SetFilePointerEx(m_hFile, Pos, nullptr, FILE_BEGIN);
        ReadDword();                   // length
        ReadShort();                   // reserved_for_future_use
        nPlaylistItems = ReadShort();  // number_of_PlayItems
        ReadShort();                   // number_of_SubPaths

        Pos.QuadPart += 10;
        for (size_t i = 0; i < nPlaylistItems; i++) {
            DWORD dwTemp;
            PlaylistItem Item;
            SetFilePointerEx(m_hFile, Pos, nullptr, FILE_BEGIN);
            Pos.QuadPart += ReadShort() + 2;
            ReadBuffer(Buff, 5);
            Item.m_strFileName.Format(_T("%s\\STREAM\\%c%c%c%c%c.M2TS"), Path, Buff[0], Buff[1], Buff[2], Buff[3], Buff[4]);

            ReadBuffer(Buff, 4);
            if (memcmp(Buff, "M2TS", 4)) {
                return CloseFile(VFW_E_INVALID_FILE_FORMAT);
            }
            ReadBuffer(Buff, 3);

            dwTemp = ReadDword();
            Item.m_rtIn = 20000i64 * dwTemp / 90; // Carefull : 32->33 bits!

            dwTemp = ReadDword();
            Item.m_rtOut = 20000i64 * dwTemp / 90; // Carefull : 32->33 bits!

            rtDuration += (Item.m_rtOut - Item.m_rtIn);

            if (Playlist.Find(Item) != nullptr) {
                bDuplicate = true;
            }
            Playlist.AddTail(Item);

            //TRACE(_T("File : %s, Duration : %s, Total duration  : %s\n"), strTemp, ReftimeToString (rtOut - rtIn), ReftimeToString (rtDuration));
        }

        CloseFile(S_OK);
        return bDuplicate ? S_FALSE : S_OK;
    }

    return AmHresultFromWin32(GetLastError());
}
コード例 #8
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 gcc_pure
 const_pointer GetExtension() const {
   return Path(*this).GetExtension();
 }
コード例 #9
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 gcc_pure
 AllocatedPath WithExtension(const_pointer new_extension) const {
   return Path(*this).WithExtension(new_extension);
 }
コード例 #10
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 /**
  * Check if this object is "inside" to the given path, and if yes,
  * return the relative path.
  */
 gcc_pure
 Path RelativeTo(Path parent) const {
   return Path(*this).RelativeTo(parent);
 }
コード例 #11
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 gcc_pure
 bool MatchesExtension(const_pointer extension) const {
   return Path(*this).MatchesExtension(extension);
 }
コード例 #12
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 gcc_pure
 Path GetBase() const {
   return Path(*this).GetBase();
 }
コード例 #13
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 AllocatedPath GetParent() const {
   return Path(*this).GetParent();
 }
コード例 #14
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 gcc_pure
 bool IsBase() const {
   return Path(*this).IsBase();
 }
コード例 #15
0
ファイル: FileSystem.cpp プロジェクト: darcyg/Caramel
Path DirectoryInfo::GetPath() const
{
    return Path( m_path );
}
コード例 #16
0
ファイル: being.cpp プロジェクト: kai62656/manabot
void Being::adjustCourse(int srcX, int srcY, int dstX, int dstY)
{
    if (debug_movement)
        printf("%p adjustCourse(%d, %d, %d, %d)\n",
                (void*) this, srcX, srcY, dstX, dstY);

    mDest.x = dstX;
    mDest.y = dstY;

    // Find a path to the destination when it is at least a tile away
    if (mMap && fabsf((mDest - mPos).length()) > 32) {
        setPath(mMap->findPath((int) mPos.x / 32, (int) mPos.y / 32,
                               dstX / 32, dstY / 32, getWalkMask()));
    } else {
        setPath(Path());
    }

    // TODO: Evaluate the implementation of this method
    /*
    if (mX / 32 == dstX / 32 && mY / 32 == dstY / 32)
    {
        // The being is already on the last tile of the path.
        Path p;
        p.push_back(Position(dstX, dstY));
        setPath(p);
        return;
    }

    Path p1;
    int p1_size, p1_length;
    Uint16 *p1_dist;
    int onPath = -1;
    if (srcX / 32 == dstX / 32 && srcY / 32 == dstY / 32)
    {
        p1_dist = new Uint16[1];
        p1_size = 1;
        p1_dist[0] = 0;
        p1_length = 0;
    }
    else
    {
        p1 = mMap->findPath(srcX / 32, srcY / 32, dstX / 32, dstY / 32, getWalkMask());
        if (p1.empty())
        {
            // No path, but don't teleport since it could be user input.
            setPath(p1);
            return;
        }
        p1_size = p1.size();
        p1_dist = new Uint16[p1_size];
        int j = 0;
        // Remove last tile so that it can be replaced by the exact destination.
        p1.pop_back();
        for (Path::iterator i = p1.begin(), i_end = p1.end(); i != i_end; ++i)
        {
            // Get distance from source to tile i.
            p1_dist[j] = mMap->getMetaTile(i->x, i->y)->Gcost;
            // Check if the being is already walking on the path.
            if (i->x == mX / 32 && i->y == mY / 32)
            {
                onPath = j;
            }
            // Do not set any offset for intermediate steps.
            i->x = i->x * 32;
            i->y = i->y * 32;
            ++j;
        }
        p1_length = mMap->getMetaTile(dstX / 32, dstY / 32)->Gcost;
        p1_dist[p1_size - 1] = p1_length;
    }
    p1.push_back(Position(dstX, dstY));

    if (mX / 32 == srcX / 32 && mY / 32 == srcY / 32)
    {
        // The being is at the start of the path.
        setPath(p1);
        delete[] p1_dist;
        return;
    }

    if (onPath >= 0)
    {
        // The being is already on the path, but it needs to be slowed down.
        for (int j = onPath; j >= 0; --j)
        {
            p1.pop_front();
        }
        int r = p1_length - p1_dist[onPath];  // remaining length
        assert(r > 0);
        setPath(p1, p1_length * 1024 / r);
        delete[] p1_dist;
        return;
    }

    Path bestPath;
    int bestRating = -1, bestStart = 0, bestLength = 0;
    int j = 0;

    for (Path::iterator i = p1.begin(), i_end = p1.end(); i != i_end; ++i)
    {
        // Look if it is worth passing by tile i.
        Path p2 = mMap->findPath(mX / 32, mY / 32, i->x / 32, i->y / 32, getWalkMask());
        if (!p2.empty())
        {
            int l1 = mMap->getMetaTile(i->x / 32, i->y / 32)->Gcost;
            int l2 = p1_length - p1_dist[j];
            int r = l1 + l2 / 2; // TODO: tune rating formula
            assert(r > 0);
            if (bestRating < 0 || r < bestRating)
            {
                bestPath.swap(p2);
                bestRating = r;
                bestStart = j;
                bestLength = l1 + l2;
            }
        }
        ++j;
    }

    if (bestRating < 0)
    {
        // Unable to reach the path? Still, don't teleport since it could be
        // user input instead of server command.
        setPath(p1);
        delete[] p1_dist;
        return;
    }

    bestPath.pop_back();
    for (Path::iterator i = bestPath.begin(), i_end = bestPath.end(); i != i_end; ++i)
    {
        i->x = i->x * 32;
        i->y = i->y * 32;
    }

    // Concatenate paths.
    for (int j = bestStart; j > 0; --j)
    {
        p1.pop_front();
    }
    p1.splice(p1.begin(), bestPath);

    assert(bestLength > 0);
    setPath(p1, p1_length * 1024 / bestLength);
    delete[] p1_dist;
    */
}
コード例 #17
0
ファイル: Variant.hpp プロジェクト: corelon/paco
	inline Path toPath() const       { check(type_ & StringType, illegalConversion()); return Path(String(*this)); }
コード例 #18
0
ファイル: CmdEdit.cpp プロジェクト: austinwagner/task
CmdEdit::editResult CmdEdit::editFile (Task& task)
{
  // Check for file permissions.
  Directory location (context.config.get ("data.location"));
  if (! location.writable ())
    throw std::string (STRING_EDIT_UNWRITABLE);

  // Create a temp file name in data.location.
  std::stringstream file;
  file << "task." << task.get ("uuid").substr (0, 8) << ".task";

  // Determine the output date format, which uses a hierarchy of definitions.
  //   rc.dateformat.edit
  //   rc.dateformat
  std::string dateformat = context.config.get ("dateformat.edit");
  if (dateformat == "")
    dateformat = context.config.get ("dateformat");

  // Change directory for the editor
  std::string current_dir = Directory::cwd ();
  int ignored = chdir (location._data.c_str ());
  ++ignored; // Keep compiler quiet.

  // Check if the file already exists, if so, bail out
  Path filepath = Path (file.str ());
  if (filepath.exists ())
    throw std::string (STRING_EDIT_IN_PROGRESS);

  // Format the contents, T -> text, write to a file.
  std::string before = formatTask (task, dateformat);
  std::string before_orig = before;
  File::write (file.str (), before);

  // Determine correct editor: .taskrc:editor > $VISUAL > $EDITOR > vi
  std::string editor = context.config.get ("editor");
  char* peditor = getenv ("VISUAL");
  if (editor == "" && peditor) editor = std::string (peditor);
  peditor = getenv ("EDITOR");
  if (editor == "" && peditor) editor = std::string (peditor);
  if (editor == "") editor = "vi";

  // Complete the command line.
  editor += " ";
  editor += "\"" + file.str () + "\"";

ARE_THESE_REALLY_HARMFUL:
  bool changes = false; // No changes made.

  // Launch the editor.
  std::cout << format (STRING_EDIT_LAUNCHING, editor) << "\n";
  int exitcode = system (editor.c_str ());
  if (0 == exitcode)
    std::cout << STRING_EDIT_COMPLETE << "\n";
  else
  {
    std::cout << format (STRING_EDIT_FAILED, exitcode) << "\n";
    if (-1 == exitcode)
      std::cout << std::strerror (errno) << "\n";
    return CmdEdit::editResult::error;
  }

  // Slurp file.
  std::string after;
  File::read (file.str (), after);

  // Update task based on what can be parsed back out of the file, but only
  // if changes were made.
  if (before_orig != after)
  {
    std::cout << STRING_EDIT_CHANGES << "\n";
    std::string problem = "";
    bool oops = false;

    try
    {
      parseTask (task, after, dateformat);
    }

    catch (const std::string& e)
    {
      problem = e;
      oops = true;
    }

    if (oops)
    {
      std::cerr << STRING_ERROR_PREFIX << problem << "\n";

      // Preserve the edits.
      before = after;
      File::write (file.str (), before);

      if (confirm (STRING_EDIT_UNPARSEABLE))
        goto ARE_THESE_REALLY_HARMFUL;
    }
    else
      changes = true;
  }
  else
  {
    std::cout << STRING_EDIT_NO_CHANGES << "\n";
    changes = false;
  }

  // Cleanup.
  File::remove (file.str ());
  ignored = chdir (current_dir.c_str ());
  return changes
         ? CmdEdit::editResult::changes
         : CmdEdit::editResult::nochanges;
}
コード例 #19
0
Path MediaConvert::getOutputFilePath(){
	return Path(destination.getPath(), (fileName + "." + getContainerName()));
}
コード例 #20
0
ファイル: FileSystem.cpp プロジェクト: darcyg/Caramel
Path FileInfo::GetPath() const
{
    return Path( m_path );
}
コード例 #21
0
ファイル: HdmvClipInfo.cpp プロジェクト: JanWillem32/mpc-hc
HRESULT CHdmvClipInfo::ReadChapters(CString strPlaylistFile, CAtlList<CHdmvClipInfo::PlaylistItem>& PlaylistItems, CAtlList<PlaylistChapter>& Chapters)
{
    CPath Path(strPlaylistFile);

    // Get BDMV folder
    Path.RemoveFileSpec();
    Path.RemoveFileSpec();

    m_hFile = CreateFile(strPlaylistFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
                         OPEN_EXISTING, FILE_ATTRIBUTE_READONLY | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);

    if (m_hFile != INVALID_HANDLE_VALUE) {
        REFERENCE_TIME* rtOffset = DEBUG_NEW REFERENCE_TIME[PlaylistItems.GetCount()];
        REFERENCE_TIME rtSum = 0;
        int nIndex = 0;
        BYTE Buff[100];
        bool bDuplicate = false;

        POSITION pos = PlaylistItems.GetHeadPosition();
        while (pos) {
            CHdmvClipInfo::PlaylistItem& PI = PlaylistItems.GetNext(pos);

            rtOffset[nIndex] = rtSum - PI.m_rtIn;
            rtSum = rtSum + PI.Duration();
            nIndex++;
        }

        ReadBuffer(Buff, 4);
        if (memcmp(Buff, "MPLS", 4)) {
            SAFE_DELETE_ARRAY(rtOffset);
            return CloseFile(VFW_E_INVALID_FILE_FORMAT);
        }

        ReadBuffer(Buff, 4);
        if ((memcmp(Buff, "0200", 4) != 0) && (memcmp(Buff, "0100", 4) != 0)) {
            SAFE_DELETE_ARRAY(rtOffset);
            return CloseFile(VFW_E_INVALID_FILE_FORMAT);
        }

        LARGE_INTEGER  Pos;
        unsigned short nMarkCount;

        ReadDword();                // PlayList_start_address
        Pos.QuadPart = ReadDword(); // PlayListMark_start_address

        // PlayListMark()
        SetFilePointerEx(m_hFile, Pos, nullptr, FILE_BEGIN);
        ReadDword();                // length
        nMarkCount = ReadShort();   // number_of_PlayList_marks
        for (size_t i = 0; i < nMarkCount; i++) {
            PlaylistChapter Chapter;

            ReadByte();                                           // reserved_for_future_use
            Chapter.m_nMarkType   = (PlaylistMarkType)ReadByte(); // mark_type
            Chapter.m_nPlayItemId = ReadShort();                  // ref_to_PlayItem_id
            Chapter.m_rtTimestamp = 20000i64 * ReadDword() / 90 + rtOffset[Chapter.m_nPlayItemId];    // mark_time_stamp
            Chapter.m_nEntryPID   = ReadShort();                  // entry_ES_PID
            Chapter.m_rtDuration  = 20000i64 * ReadDword() / 90;  // duration

            Chapters.AddTail(Chapter);

            //TRACE(_T("Chapter %d : %s\n"), i, ReftimeToString(Chapter.m_rtTimestamp));
        }

        CloseFile(S_OK);
        SAFE_DELETE_ARRAY(rtOffset);
        return bDuplicate ? S_FALSE : S_OK;
    }

    return AmHresultFromWin32(GetLastError());
}
コード例 #22
0
ファイル: FileSystem.cpp プロジェクト: darcyg/Caramel
Path Path::Directory() const { return Path( std::make_shared< PathImpl >( m_impl->parent_path() )); }
コード例 #23
0
ファイル: System.cpp プロジェクト: septag/stcore
Path System::GetTempDir()
{
    return Path("/tmp");
}
コード例 #24
0
ファイル: FileSystem.cpp プロジェクト: darcyg/Caramel
Path Path::Filename()  const { return Path( std::make_shared< PathImpl >( m_impl->filename() )); }
コード例 #25
0
ファイル: XData.cpp プロジェクト: codereader/DarkRadiant
//XData implementations:
//->export:
FileStatus XData::xport( const std::string& filename, ExporterCommand cmd )
{
	fs::path Path(filename);

	fs::path parent = Path.parent_path();

	// Ensure the parent path exists
	fs::create_directories(parent);

	if (os::fileOrDirExists(Path.string()))
	{
		switch (cmd)
		{
		case Merge:
			{
			//Check if definition already exists and return DefinitionExists. If it does not, append the definition to the file.
				std::fstream file(Path.string(), std::ios_base::in | std::ios_base::out | std::ios_base::app);
				if (!file.is_open())
					return OpenFailed;
				std::stringstream ss;
				ss << file.rdbuf();
				std::string String = ss.str();
				std::size_t DefPos = String.find(_name);
				while (DefPos != std::string::npos)	//A name of a XData could be contained in another XData's name. Check that...
				{
					char before = String[DefPos > 0 ? DefPos-1 : 0];
					char after = String[DefPos+_name.length() < String.size() ? DefPos+_name.length() : 0];
					if ((DefPos == 0 || before == ' ' || before == '\t' || before == '\n') && (DefPos+_name.length() == String.size() || after == ' ' || after == '\t' || after == '\n'))	//other delimiters necessary?
					{
						_definitionStart = 0;
						//Definition found. But we want to have it clean, so let's see how many spaces are before the definition begin.
						while (DefPos > 0)
						{
							if (String[--DefPos] != ' ' && String[DefPos] != '\t' && String[DefPos] != '\n')
							{
								_definitionStart = DefPos+1;
								break;
							}
						}

						file.close();
						return DefinitionExists;
					}
					DefPos = String.find(_name,DefPos+_name.length());
				}
				file << "\n\n\n" << generateXDataDef();
				file.close();
				return AllOk;
			}
		case MergeOverwriteExisting:
			{
			//Find the old definition in the target file and delete it. Append the new definition.
			//_definitionStart has been set in the first iteration of this method.
				std::fstream file(Path.string(), std::ios_base::in);
				if (!file.is_open())
					return OpenFailed;
				std::stringstream ss;
				ss << file.rdbuf();
				std::string OutString = ss.str();
				file.close();
                std::size_t DefLength = getDefLength(OutString.substr(_definitionStart));
				if (DefLength == 0)		//If the definitionlength can't be obtained, the merge fails.
					return MergeFailed;
				OutString.erase(_definitionStart, DefLength);
				std::string insString = std::string( (_definitionStart != 0) ? "\n\n\n" : "" )		//No new lines in the first line
					+ generateXDataDef()
					+ std::string( (_definitionStart == OutString.size()) ? "" : "\n\n\n" );		//No new lines at the end of file
				OutString.insert(_definitionStart, insString);
				file.open(Path.string(), std::ios_base::out | std::ios_base::trunc);
				if (!file.is_open())
					return OpenFailed;
				file << OutString;
				file.close();
				return AllOk;
			}
		case Overwrite:
			{
			//Warn if the target file contains multiple definitions: return MultipleDefinitions.
			//Warn if the definition in the target file does not match the current definition: return DefinitionMisMatch
			//else overwrite existing file.
				std::string DefName;
				std::ifstream file(Path.string(), std::ios_base::in);
				if (!file.is_open())
					return OpenFailed;
				try	{ DefName = getDefinitionNameFromXD(file); }
				catch (...)
				{
                    rConsoleError() << "[XData::xport] Syntax error in file " << filename 
                        << ". Overwriting the file..." << std::endl;
					break;
				}
				if (DefName == _name)	//Definition will be overwritten...
					break;
				else if (DefName == "")	//MultipleDefinitions exist
					return MultipleDefinitions;
				return DefinitionMismatch;
			}
		case OverwriteMultDef:
			//Replace the file no matter what.
			break;
		default: return FileExists;
		}
	}

	//Write the definition into the file.
	std::ofstream file(Path.string(), std::ios_base::out | std::ios_base::trunc);
	if (!file.is_open())
		return OpenFailed;
	file << generateXDataDef();
	file.close();

	return AllOk;
}
コード例 #26
0
ファイル: FileSystem.cpp プロジェクト: darcyg/Caramel
Path Path::Stem()      const { return Path( std::make_shared< PathImpl >( m_impl->stem() )); }
コード例 #27
0
ファイル: FileZillaIntf.cpp プロジェクト: anyue100/winscp
//---------------------------------------------------------------------------
bool __fastcall TFileZillaIntf::RemoveDir(const wchar_t* FileName, const wchar_t* APath)
{
  DebugAssert(FFileZillaApi != NULL);
  CServerPath Path(APath);
  return Check(FFileZillaApi->RemoveDir(FileName, Path), L"removedir");
}
コード例 #28
0
ファイル: FileSystem.cpp プロジェクト: darcyg/Caramel
Path Path::Extension() const { return Path( std::make_shared< PathImpl >( m_impl->extension() )); }
コード例 #29
0
ファイル: FileZillaIntf.cpp プロジェクト: anyue100/winscp
//---------------------------------------------------------------------------
bool __fastcall TFileZillaIntf::SetCurrentPath(const wchar_t * APath)
{
  DebugAssert(FFileZillaApi != NULL);
  CServerPath Path(APath);
  return Check(FFileZillaApi->SetCurrentPath(Path), L"setcurrentpath");
}
コード例 #30
0
ファイル: Path.hpp プロジェクト: ToninoTarsi/XCSoar
 operator Path() const {
   return Path(c_str());
 }