diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index eea399e210ae..00295965f69a 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,76 +1,23 @@ # Contributing to LinuxFiles -LinuxFiles is an unofficial, community-maintained Linux port of [Files](https://github.com/files-community/Files); it is not affiliated with the Files Community. The guidance below is adapted from upstream's contributing guide and still applies unless noted. -- Issues and pull requests for the **Linux port** go to this repository. Issues about the Windows app belong [upstream](https://github.com/files-community/Files/issues). -- Please read [docs/linux-port/PLAN.md](../docs/linux-port/PLAN.md) and [docs/linux-port/AGENT-RULES.md](../docs/linux-port/AGENT-RULES.md) first. Linux code lives in `*.Linux.cs` files and the Linux platform projects; keep Windows code paths unchanged. -- Upstream's "Ready to build" label and Windows-only tooling (Appium, WinAppDriver, the Files.Package) do not apply to this fork. Open an issue to discuss larger changes first. -- Do not copy code from upstream without keeping its MIT notice, and do not claim upstream work as your own. Changes that are not Linux-specific are best sent upstream too. -- Security issues: see [SECURITY.md](./SECURITY.md). +LinuxFiles is an independent Linux-only fork of [Files](https://github.com/files-community/Files), unaffiliated with the Files Community. There is no upstream sync or Windows support. Preserve inherited license headers, notices and contributor credit. -Files thrives off of the contributions and input from users. There are several ways you can get involved. +Report issues and submit pull requests in [this repository](https://github.com/MemerGamer/LinuxFiles). Discuss larger changes before implementing them, and follow our [Code of Conduct](CODE_OF_CONDUCT.md). Report security issues privately as described in [SECURITY.md](SECURITY.md). -We are happy to hear your feedback for the future of Files. Check the -[issues tab](https://github.com/MemerGamer/LinuxFiles/issues) to see if others have -submitted similar feedback. You can add your feedback to existing issues or you can open a new issue. +Read [AGENTS.md](../AGENTS.md), [Linux agent rules](../docs/linux-port/AGENT-RULES.md) and the [fork policy](../docs/linux-port/upstream-policy.md). The porting plans are archived historical context. -We always look at your feedback when we decide what to work on next and we look forward to hearing your ideas. Remember that -all community interactions must abide by the [Code of Conduct](./CODE_OF_CONDUCT.md). +## Build and validation -## Finding issues you can help with -Looking for something to work on? -Issues marked as ready to build are a good place to start. If you're interested in working on an issue, leave a comment to let everyone know and to help -avoid duplicated effort from others. +Use the .NET 10 SDK and the Linux desktop dependencies described in [README.md](README.md). -## Contributions we accept -We welcome your contributions to the Files project, especially to fix bugs and to make -improvements which address the top issues reported by Files users. Some general guidelines: - -* **DO** create one pull request per Issue, and ensure that the Issue is linked in the pull request. -* **DO** follow our [Coding and Style](https://files.community/docs/contributing/code-style) guidelines, and keep code changes as small as possible. -* **DO** include corresponding tests whenever possible. -* **DO** check for additional occurrences of the same problem in other parts of the codebase before submitting your PR. -* **DO** [link the issue](https://docs.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#manually-linking-a-pull-request-to-an-issue) you are addressing in the - pull request. -* **DO** write a good description for your pull request. More detail is better. Describe *why* the change is being - made and *why* you have chosen a particular solution. Describe any manual testing you performed to validate your change. -* **DO NOT** submit a PR unless the connected issue is marked as ready to build or approved by an org member. - This enables us to have a discussion on the idea before anyone invests time on the implementation. -* **DO NOT** merge multiple changes into one PR unless they have the same root cause. - -> Submitting a pull request for an approved Issue is not a guarantee it will be approved. -> The change must meet our high bar for code quality, architecture, and performance. - -## Making changes to the code - -If your change is complex, please clean up the branch history before submitting a pull request. -You can use [git rebase](https://docs.microsoft.com/en-us/azure/devops/repos/git/rebase#squash-local-commits) -to group your changes into a small number of commits which we can review one at a time. - -When completing a pull request, we will generally squash your changes into a single commit. Please -let us know if your pull request needs to be merged as separate commits. - -## Running interaction tests (optional) -The tests drive the app through [Appium](https://appium.io), which automates it using WinAppDriver. -Install WinAppDriver, and Node.js to run Appium on: -```powershell -winget install Microsoft.WindowsApplicationDriver -winget install OpenJS.NodeJS -``` -Then install Appium and the Windows driver it automates through: -```powershell -npm install --global appium -appium driver install --source=npm appium-windows-driver +```sh +dotnet build src/Files.App -f net10.0-desktop +dotnet build tests/Files.Platform.Tests +dotnet test --project tests/Files.Platform.Tests/Files.Platform.Tests.csproj --no-build ``` -The tests launch Appium themselves when it is not already running, so keep it on your `PATH`. -Finally, you will need to run the Files.Package at least once to have the debug version be registered on your machine. -Once you have the debug version registered, you can run the tests from the test explorer in Visual Studio. +Run builds sequentially. For UI validation, use `scripts/linux/headless-run.sh` with its private Xvfb display and throwaway home; do not alter the user's desktop or settings. -## Review Process -After submitting a pull request, members of the Files team will review your code. Any member of the community may -participate in the review, but at least one member of the Files team will ultimately approve -the request. +## Pull requests -Often, multiple iterations will be needed to respond to feedback from reviewers. Try looking at -[past pull requests](https://github.com/files-community/Files/pulls?q=is%3Apr+is%3Aclosed) to see -what the experience might be like. +Keep each change focused, follow `.editorconfig` and surrounding code, and include relevant validation. Use [the PR template](PULL_REQUEST_TEMPLATE.md), link the issue where applicable, and explain the resulting behavior and any limitations. Maintainers review contributions in this fork; upstream approval or labels are not required. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 3cef89a4d84f..52e627d6d13f 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,5 +1,5 @@ name: Bug Report -description: Report a bug in LinuxFiles, the unofficial Linux port of Files. +description: Report a bug in LinuxFiles, the independent Linux fork of Files. type: 'Bug' title: 'Bug: ' body: @@ -9,7 +9,7 @@ body: attributes: value: | > [!NOTE] - > This tracker is for the Linux port. Windows-only bugs belong in the [upstream Files tracker](https://github.com/files-community/Files/issues), and only if reproducible in the official Windows app. + > This tracker is for LinuxFiles, an independent Linux-only fork. > [!TIP] > Have you checked for similar issues? There's a possibility the bug you are experiencing has already been reported. Please do a thorough search before creating a new issue. @@ -44,13 +44,13 @@ body: validations: required: true - # Windows Version + # Linux Environment - type: input - id: windows_version + id: linux_environment attributes: - label: Windows Version - description: Which version of Windows are you using? To copy your Windows version, access it from Settings -> About -> Copy -> Windows version. - placeholder: "e.g. 10.0.22621.1848" + label: Linux Environment + description: Which Linux distribution, desktop environment and display session (X11 or Wayland/XWayland) are you using? + placeholder: "e.g. Fedora 43, KDE Plasma, Wayland/XWayland" validations: required: true diff --git a/.github/README.md b/.github/README.md index f0ea097e90b8..232a28adf9a3 100644 --- a/.github/README.md +++ b/.github/README.md @@ -4,14 +4,14 @@ # LinuxFiles: Files for Linux -**LinuxFiles, Files for Linux, based on Files by the Files Community, is an unofficial, community-maintained Linux port of [Files](https://github.com/files-community/Files) by the Files Community. It is not affiliated with or endorsed by the Files Community.** +**LinuxFiles, Files for Linux, based on Files by the Files Community, is an independent, community-maintained Linux-only fork of [Files](https://github.com/files-community/Files) by the Files Community. It is not affiliated with or endorsed by the Files Community.** Files is created and maintained by the [Files Community](https://github.com/files-community) and its [contributors](https://github.com/files-community/Files/graphs/contributors). This fork builds on their work and keeps their MIT-licensed code, history and credit. The Linux port itself ([Uno Platform](https://platform.uno), Skia, X11, and the Linux platform layer) is the work of the LinuxFiles contributors. See [Credits](#credits) and [NOTICE.md](../NOTICE.md). > [!WARNING] > **Status: alpha.** Expect missing features and rough edges, and do not rely on it for data you cannot afford to lose. The official, supported Files for Windows is at [files.community](https://files.community/). -LinuxFiles is now an independent fork: upstream stays a read-only remote, fixes are cherry-picked selectively, and upstream branches are no longer merged. See the [upstream policy](../docs/linux-port/upstream-policy.md). MIT/MPL licenses and contributor notices remain preserved. +LinuxFiles supports Linux only and has no upstream sync: upstream stays a read-only remote, fixes are cherry-picked selectively, and upstream branches are no longer merged. See the [upstream policy](../docs/linux-port/upstream-policy.md). MIT/MPL licenses and contributor notices remain preserved. ## Linux port: current state @@ -128,22 +128,11 @@ curl -LO https://github.com/MemerGamer/LinuxFiles/releases/download/nightly/Linu ## Reporting bugs - **Linux bugs and Linux feature requests:** open an issue in [this fork](https://github.com/MemerGamer/LinuxFiles/issues). -- **Windows bugs:** report them to [upstream Files](https://github.com/files-community/Files/issues) only if you can reproduce them in the official Windows app. Please do not report LinuxFiles problems upstream. - **Security issues:** use this fork's private [Security Advisories](https://github.com/MemerGamer/LinuxFiles/security/advisories/new). See [SECURITY.md](./SECURITY.md). -## About upstream Files - -The text and images in this section describe the upstream project and are the Files Community's work, not ours. - -![Upstream Files screenshot (Windows)](./assets/FilesScreenshot.png) - -Files is a modern file manager that helps users organize their files and folders. The upstream mission is to build the best file manager for Windows, built in the open by the community, with robust multitasking, file tags, deep integrations and an intuitive design. See the [upstream repository](https://github.com/files-community/Files) and [website](https://files.community/). - -For the official Windows app, use the upstream distribution channels (Microsoft Store and classic installer from [files.community/download](https://files.community/download)); this fork does not distribute Windows builds. - ## Contributing -Contributions to the Linux port are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md). Contributions to the Windows app belong in the [upstream repository](https://github.com/files-community/Files). +Contributions to this independent Linux fork are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md). ## Credits diff --git a/.github/assets/ClassicInstallerBadge-dark.png b/.github/assets/ClassicInstallerBadge-dark.png deleted file mode 100644 index a1ecea01a2b8..000000000000 Binary files a/.github/assets/ClassicInstallerBadge-dark.png and /dev/null differ diff --git a/.github/assets/ClassicInstallerBadge-light.png b/.github/assets/ClassicInstallerBadge-light.png deleted file mode 100644 index be0886d1bd36..000000000000 Binary files a/.github/assets/ClassicInstallerBadge-light.png and /dev/null differ diff --git a/.github/assets/FilesScreenshot.png b/.github/assets/FilesScreenshot.png deleted file mode 100644 index 21109046b11a..000000000000 Binary files a/.github/assets/FilesScreenshot.png and /dev/null differ diff --git a/.github/assets/ReadmeHero.png b/.github/assets/ReadmeHero.png deleted file mode 100644 index ccd33a74cfbc..000000000000 Binary files a/.github/assets/ReadmeHero.png and /dev/null differ diff --git a/.github/assets/StoreBadge-dark.png b/.github/assets/StoreBadge-dark.png deleted file mode 100644 index d739cc59ab80..000000000000 Binary files a/.github/assets/StoreBadge-dark.png and /dev/null differ diff --git a/.github/assets/StoreBadge-light.png b/.github/assets/StoreBadge-light.png deleted file mode 100644 index 2fe14bbb0b10..000000000000 Binary files a/.github/assets/StoreBadge-light.png and /dev/null differ diff --git a/AGENTS.md b/AGENTS.md index 2952659bb32b..34873238d069 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,123 +1,31 @@ -# Files Development Guidelines +# LinuxFiles development -This project is a C#/.NET WinUI 3 desktop app; an alternative to File Explorer. +LinuxFiles is an independent Linux-only file manager built with C#/.NET and Uno Platform (Skia desktop, X11/XWayland). There is no upstream sync or Windows support. Preserve inherited licenses, notices and contributor attribution; see [upstream policy](docs/linux-port/upstream-policy.md). -- Protect context usage. Any command with unknown or potentially large output must be capped. Prefer targeted commands such as `rg`, `Get-Content -TotalCount`, `Select-Object -First`, or focused `git diff -- `; for example, `COMMAND 2>&1 | Select-Object -First 200`. If a line cap is still too noisy, narrow the query instead of dumping full output. -- Always follow `.editorconfig` -- Keep changed text files in CRLF line endings -- Keep comments concise and useful. Do not add comments that restate obvious code. -- Never read entire generated files in `bin` or `obj` unless the generated source is directly needed. -- Prefer targeted search over full file reads. -- Touch only what you must. Clean up only files you created or changed for the task. -- Treat file operations, shell integration, drag/drop, preview handlers, archive actions, settings persistence, and localization as high-risk areas. -- For Win32, COM, Shell, clipboard, hotkey, and file operation interop, prefer `src/Files.App.CsWin32`, `NativeMethods.txt`, and existing wrappers/helpers. -- Avoid ad hoc P/Invoke declarations when CsWin32 or existing interop code can cover the API. -- Do not edit generated CsWin32 output directly. Update source declarations, wrappers, or generator inputs instead. -- For UI work, use existing XAML resources, controls, converters, commands, and localization patterns. Avoid one-off styles or hard-coded user-visible strings. -- Start by identifying the smallest relevant project, feature area, and files for the task. -- Read nearby code before adding new abstractions. Prefer existing WinUI, MVVM, service, command, and storage patterns. -- Keep implementation scoped to the requested behavior. Avoid opportunistic refactors, formatting churn, dependency updates, and generated file edits. -- Treat tool output as evidence. When behavior changes, run the focused build that can prove it and report anything left unverified. +## Scope and style -## Code Review Rules +- Identify the smallest relevant project and read nearby code before changing it. +- Follow `.editorconfig`, existing MVVM, service, command and localization patterns. Keep comments concise and avoid hard-coded user-visible strings. +- Preserve CRLF on files that use it. Avoid generated files, unrelated cleanup and dependency changes. +- Use targeted `rg` searches and cap potentially large command output. Before deleting files or types, check all references, including XAML, project exclusions and tests, for Linux consumers. +- Treat file operations, clipboard, drag/drop, previews, archives, settings persistence and localization as high-risk areas. +- Route OS functionality through `Files.Platform.Abstractions` and `Files.Platform.Linux`. Prefer existing native wrappers and source-generated `LibraryImport`; avoid ad hoc interop and runtime reflection that cannot be proven safe for trimming/AOT. +- Treat filenames, desktop entries and archive contents as untrusted. Avoid shell interpolation; use existing fd-relative helpers for recursive destructive operations. -### Native interop +## Build and verify -- Reject new uses of `DllImport`. Prefer existing interop wrappers or CsWin32, and use `LibraryImport` only when CsWin32 cannot generate or safely express the required API. -- Reject new uses of `ComImport`. Prefer CsWin32-generated COM interfaces or `GeneratedComInterface`, and use a focused AOT-safe vtable wrapper only when source-generated COM cannot represent the interface. -- Add app runtime CsWin32 APIs to `src/Files.App.CsWin32/NativeMethods.txt`, and keep test-only APIs in the relevant test project's `NativeMethods.txt`; do not edit generated CsWin32 output. -- When introducing a required native module, add the matching `DirectPInvoke` entry to `src/Files.App/Files.App.csproj`. Do not direct-bind optional modules or entry points that are not guaranteed to exist on every supported Windows version. - -### Reflection and Native AOT - -- Flag new runtime reflection used for member discovery, invocation, dynamic activation, or runtime code generation unless trimming and AOT analysis can statically prove it safe. Simple type inspection such as `obj.GetType().Name` is out of scope. -- Prefer source generation, static dispatch, or explicitly registered types. When reflection is necessary, use `DynamicallyAccessedMembers`, `DynamicDependency`, or another narrowly justified preservation mechanism as required and keep trimming and AOT diagnostics clean. -- `RequiresDynamicCode` and `RequiresUnreferencedCode` declare incompatibility; they do not make reflection AOT-safe and are not acceptable exemptions. -- Keep suppressions of trimming or AOT diagnostics local, document why the reflected members remain available, and verify the relevant AOT build. - -## Codebase Structure - -```text -/src -├── Files.App Main WinUI app -├── Files.App.Controls Shared app controls -├── Files.App.Storage App storage abstractions and implementations -├── Files.App.CsWin32 Generated/native Win32 interop project -├── Files.Core.SourceGenerator Roslyn source generators and analyzers -├── Files.Core.Storage Core storage abstractions -└── Files.Shared Shared attributes, extensions, and common code +```sh +dotnet build src/Files.App -f net10.0-desktop +dotnet build tests/Files.Platform.Tests +dotnet test --project tests/Files.Platform.Tests/Files.Platform.Tests.csproj --no-build ``` -```text -/tests -└── Files.Platform.Tests Linux platform tests -``` - -## Build - -Prefer explicit platform/configuration builds. -Unless the task is specifically about resolving or inspecting warnings, add `-v:quiet -clp:ErrorsOnly` to `msbuild` commands so the log proves success or shows only actionable errors. - -```powershell -msbuild -restore Files.slnx -p:Configuration=Debug -p:Platform=x64 -v:quiet -clp:ErrorsOnly -``` - -If `msbuild` isn't available in the current shell, run it from Visual Studio Developer PowerShell. Match `-arch`, `-host_arch`, and `-p:Platform` to the platform you're verifying; use `x64` for x64 work and `arm64` for ARM64 work. - -```powershell -pwsh.exe -NoProfile -Command "& { - Import-Module 'C:\Program Files\Microsoft Visual Studio\18\Professional\Common7\Tools\Microsoft.VisualStudio.DevShell.dll' - Enter-VsDevShell 1ba2cc4e -SkipAutomaticLocation -DevCmdArguments '-arch=x64 -host_arch=x64' - msbuild -restore src/Files.App/Files.App.csproj -p:Configuration=Debug -p:Platform=x64 -v:quiet -clp:ErrorsOnly -}" -``` - -For focused C# work, build the affected project first. -Do not run build commands in parallel. - -```powershell -msbuild -restore src/Files.Shared/Files.Shared.csproj -p:Configuration=Debug -p:Platform=x64 -v:quiet -clp:ErrorsOnly -msbuild -restore src/Files.Core.SourceGenerator/Files.Core.SourceGenerator.csproj -p:Configuration=Debug -p:Platform=x64 -v:quiet -clp:ErrorsOnly -msbuild -restore src/Files.App/Files.App.csproj -p:Configuration=Debug -p:Platform=x64 -v:quiet -clp:ErrorsOnly -``` +Build affected projects first and run builds sequentially. Report checks performed and anything unverified. If the desktop toolchain is unavailable, use reference searches and state that the build was not run. -## Test +Use `scripts/linux/headless-run.sh` for UI checks on a private display with a throwaway home. Do not launch against the user's display or alter their desktop settings. Clean up processes you start and never commit private home data or screenshots. -We currently don't have a suitable set of tests for AI agents. Just make sure that the builds succeed. +## Git and reviews -## Commit & Push - -When asked to commit, run these commands beforehand: - -```powershell -git status --short -git diff --check -``` - -Do not revert unrelated user changes. Stage only files that belong to the requested change. - -Use concise commit messages that describe the behavior change, for example: - -```text -Add source-generated settings storage -``` - -## Open a PR - -When asked to open a PR, use a short PR title that names the behavior, not the implementation mechanics only, and prepend the PR type: - -- "Fix": use this prefix when the linked issue is a bug -- "Feature": use this prefix when the linked issue is a feature request -- "Code Quality": anything else - -The repository maintainers draft release notes based on these PR types: only fixes and feature requests are listed. - -Good examples: - -```text -Fix: Fixed an issue where thumbnails wouldn't refresh when a file was updated -Feature: Add support for previewing AVI files in the Preview Pane -Code Quality: Add source-generated settings serialization -``` +Do not revert unrelated changes. Commit or push only when requested; stage only task files. Before a commit, run `git status --short` and `git diff --check`. Use a concise message describing the behavior change. -For the PR body, follow `./.github/PULL_REQUEST_TEMPLATE.md`. +For requested PRs, use `.github/PULL_REQUEST_TEMPLATE.md` and prefix the title with `Fix:`, `Feature:` or `Code Quality:`. Target this fork, never upstream. Include validation and remaining limitations. diff --git a/Directory.Build.props b/Directory.Build.props index 1c84d532f745..d8e3a44c7449 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,13 +4,7 @@ net10.0 - 10.0.26100.0 - 10.0.19041.0 - 10.0.26100.67-preview - $(BaseTargetFramework)-windows$(TargetWindowsVersion) $(BaseTargetFramework)-desktop - - false preview nullable @@ -21,8 +15,5 @@ strict - - 3 - diff --git a/Directory.Packages.props b/Directory.Packages.props index ea69ce3cd55f..09d96f4089ef 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,9 +5,6 @@ - - - @@ -26,40 +23,27 @@ - - - - - - - - - - - - - diff --git a/Files.slnx b/Files.slnx index 4890a9f11ef1..f55a46d960a1 100644 --- a/Files.slnx +++ b/Files.slnx @@ -34,11 +34,6 @@ - - - - - diff --git a/docs/linux-port/AGENT-RULES.md b/docs/linux-port/AGENT-RULES.md index 8c5a1ddadec3..1beb3832d271 100644 --- a/docs/linux-port/AGENT-RULES.md +++ b/docs/linux-port/AGENT-RULES.md @@ -1,36 +1,28 @@ -# Rules for agents working on the Linux port - -Read this first, then `PLAN.md` §0, then `CLAUDE.md`. - -## Machine etiquette (the owner uses this machine, often for games, while agents work) -- Never run the app on the real display. Don't use `DISPLAY=:0` or `WAYLAND_DISPLAY`, and don't run xdotool, screenshots or input against it. Run the app only through `scripts/linux/headless-run.sh`, which uses a private Xvfb display, a sandboxed throwaway HOME and cleans up after itself. Its `-a` actions file sends xdotool input and takes screenshots on the private display. -- Never change desktop or system settings (gsettings, kwriteconfig, portal writes, xdg-mime defaults, ~/.config of the real user). -- Build at low priority without leftover MSBuild nodes: - `MSBUILDDISABLENODEREUSE=1 nice -n 19 dotnet build src/Files.App -f net10.0-desktop -nodeReuse:false -m:2` -- Tests: `MSBUILDDISABLENODEREUSE=1 nice -n 19 dotnet build tests/Files.Platform.Tests -nodeReuse:false -m:2 -warnaserror` then `nice -n 19 dotnet test --project tests/Files.Platform.Tests/Files.Platform.Tests.csproj --no-build`. -- Kill every process you start. Leave nothing running. -- At most one app build or test run at a time per agent (`-m:2` caps CPU). Avoid needless full rebuilds. - -## Privacy -- Only commit screenshots made with the sandboxed HOME. headless-run.sh gives the app synthetic drives (`FILES_SANDBOX_DRIVES`, honoured only in sandboxed headless mode), so real drive labels no longer appear; still view every PNG before committing. `scripts/linux/showcase.sh` regenerates the showcase shots. -- Never commit anything from the real home directory. - -## Git / GitHub -- Branch from `origin/main` (the single integration branch; releases are tags: `nightly` rolling, `linux-v*` stable): `git fetch origin && git switch -c linux/ origin/main`. -- Commit trailer: `Co-Authored-By: Claude Sonnet 5.5 `. -- Push: `git -c credential.helper='!gh auth git-credential' push -u origin linux/`. -- PR: `gh pr create -R MemerGamer/LinuxFiles --base main --head linux/ ...`. The body ends with `🤖 Generated with [Claude Code](https://claude.com/claude-code)`. -- Never target, push to, or comment on upstream `files-community/Files`. - -## Code -- Linux-first: the Windows build need not stay green, but keep Windows code paths intact (`#if WINDOWS`, `*.Linux.cs` partials, desktop-only Compile items). -- Route OS functionality through `Files.Platform.Abstractions` services implemented in `Files.Platform.Linux` (unit-tested in `tests/Files.Platform.Tests`). Don't call Win32 on Linux. -- Native interop only via `[LibraryImport]` in `src/Files.Platform.Linux/Native/`. No `DllImport`/`ComImport`. -- Mark stubs `// LINUX-TODO(): ...`. -- Keep edits to shared files scoped. New strings in `Strings/en-US/Resources.resw` are append-only. -- This fork is independent: no upstream merges or automatic sync. Selectively cherry-pick reviewed fixes with attribution; follow [upstream-policy.md](upstream-policy.md). -- Security: treat file names, `.desktop` files, archives and anything from disk as untrusted. No shell interpolation. Use fd-relative ops for recursive destructive actions (`Native/PosixNative`). -- Match the surrounding style (license header, tabs, block namespaces). - -## Report back -PR URL, what works (with headless screenshot paths), what's stubbed (LINUX-TODOs), remaining issues, and any hooks you need from other workstreams. +# Linux developer rules + +Read [AGENTS.md](../../AGENTS.md) and the [independent-fork policy](upstream-policy.md). Porting plans are archived context. LinuxFiles supports Linux only and has no upstream sync. + +## Machine and privacy + +- Use `scripts/linux/headless-run.sh` for app runs. It supplies a private Xvfb display, throwaway home and cleanup. Never run against the user's display or capture their desktop. +- Do not alter the user's desktop settings, default applications or real home configuration. +- Inspect headless screenshots before sharing them. Never commit private home data. +- Run builds sequentially and clean up processes you start. + +## Validation + +```sh +dotnet build src/Files.App -f net10.0-desktop +dotnet build tests/Files.Platform.Tests +dotnet test --project tests/Files.Platform.Tests/Files.Platform.Tests.csproj --no-build +``` + +Use focused reference searches when the desktop toolchain is unavailable, and report that limitation. Before deletion, check source, XAML, project exclusions and tests for Linux consumers. + +## Implementation and review + +- Use existing services in `Files.Platform.Abstractions` and implementations in `Files.Platform.Linux`. +- Prefer existing native wrappers and `LibraryImport`. Treat filenames, desktop entries and archives as untrusted; avoid shell interpolation. +- Follow surrounding style and localization patterns. Preserve licenses, notices and attribution. +- Keep changes scoped and preserve CRLF where present. Commit, push or open PRs only when requested, targeting this fork. +- Report behavior changes, verification, unresolved issues and dependencies on other workstreams. diff --git a/docs/linux-port/PLAN-alpha3.md b/docs/linux-port/PLAN-alpha3.md index 439b674c248c..97ae2bbabd51 100644 --- a/docs/linux-port/PLAN-alpha3.md +++ b/docs/linux-port/PLAN-alpha3.md @@ -1,3 +1,5 @@ +> **Archived historical document.** This records an earlier plan or investigation, not current developer guidance. LinuxFiles is an independent Linux-only fork with no upstream sync or Windows support. See the [current policy](upstream-policy.md) and [developer guidance](../../AGENTS.md). + > Historical alpha3 plan. The [upstream policy](upstream-policy.md) supersedes its upstream-sync and soft-only Windows removal guidance. # Plan: 0.1.0-alpha3 and the road to 0.2 diff --git a/docs/linux-port/PLAN-rust-and-trim.md b/docs/linux-port/PLAN-rust-and-trim.md index 4545d5b76652..491b3c69ef2e 100644 --- a/docs/linux-port/PLAN-rust-and-trim.md +++ b/docs/linux-port/PLAN-rust-and-trim.md @@ -1,3 +1,5 @@ +> **Archived historical document.** This records an earlier plan or investigation, not current developer guidance. LinuxFiles is an independent Linux-only fork with no upstream sync or Windows support. See the [current policy](upstream-policy.md) and [developer guidance](../../AGENTS.md). + # Plan: keep Uno, Rust backend, drop Windows code Decision (user, 2026-10-09): keep Uno for the UI, move hot backend paths to Rust, and remove Windows-specific code from the independent fork. Supersedes the "Rust no-go until benchmark" verdict in `investigations/rust.md` only in direction; the benchmark gate still applies per component. diff --git a/docs/linux-port/PLAN.md b/docs/linux-port/PLAN.md index 5daea1ed15f1..f7cd55a80234 100644 --- a/docs/linux-port/PLAN.md +++ b/docs/linux-port/PLAN.md @@ -1,3 +1,5 @@ +> **Archived historical document.** This records an earlier plan or investigation, not current developer guidance. LinuxFiles is an independent Linux-only fork with no upstream sync or Windows support. See the [current policy](upstream-policy.md) and [developer guidance](../../AGENTS.md). + # Files on Linux — Porting Plan > **Branching (2026-10-05):** `main` is the single integration branch. `linux/main` is retired (frozen at the last merge). Releases are tags: the rolling `nightly` pre-release (every push to `main`) and stable `linux-v*` tags. diff --git a/docs/linux-port/dnd.md b/docs/linux-port/dnd.md index e2dfc2379d95..d4bb65261966 100644 --- a/docs/linux-port/dnd.md +++ b/docs/linux-port/dnd.md @@ -10,7 +10,7 @@ Uno 6.7's X11 host cannot publish file lists on the clipboard (`X11ClipboardExte | `IClipboardService`, `IFileDragSource` | `src/Files.Platform.Abstractions/Clipboard` | | Format logic (pure, unit tested) | `Files.Platform.Linux/Clipboard/ClipboardFormats.cs` | | X11 selection owner, requestor and XDND source | `Files.Platform.Linux/Clipboard/X11SelectionHost.cs` (Xlib via `LibraryImport` in `Native/X11Native.cs`) | -| Files glue (`#if !WINDOWS` one-line hooks) | `Files.App/Platforms/Desktop/Services/DesktopFileDragHelper.cs` | +| Files desktop glue | `Files.App/Platforms/Desktop/Services/DesktopFileDragHelper.cs` | | Crash guard for Uno's failed native drag | `Files.App/Platforms/Desktop/DesktopRuntimeGuards.cs` | ### Why our own Xlib connection and no managed X11 client diff --git a/docs/linux-port/investigations/remove-windows-code.md b/docs/linux-port/investigations/remove-windows-code.md index a6ae87a6c975..36d7dea24ccd 100644 --- a/docs/linux-port/investigations/remove-windows-code.md +++ b/docs/linux-port/investigations/remove-windows-code.md @@ -1,3 +1,5 @@ +> **Archived historical document.** This records an earlier plan or investigation, not current developer guidance. LinuxFiles is an independent Linux-only fork with no upstream sync or Windows support. See the [current policy](../upstream-policy.md) and [developer guidance](../../../AGENTS.md). + > Historical investigation. The [independent-fork policy](../upstream-policy.md) supersedes the sync-preservation recommendation below; Windows leaf projects and sync/pruning automation have since been removed. **Recommend option 1: retain the upstream tree, tighten Linux publish exclusions, then investigate trimming.** Deleting sources already excluded from compilation offers essentially **zero binary-size or startup gain**. diff --git a/docs/linux-port/phase2-errors.md b/docs/linux-port/phase2-errors.md index 2ae4e5c76a07..6f9c1609b00d 100644 --- a/docs/linux-port/phase2-errors.md +++ b/docs/linux-port/phase2-errors.md @@ -1,3 +1,5 @@ +> **Archived historical document.** This records an earlier plan or investigation, not current developer guidance. LinuxFiles is an independent Linux-only fork with no upstream sync or Windows support. See the [current policy](upstream-policy.md) and [developer guidance](../../AGENTS.md). + # Phase 2: Files.App on Uno (net10.0-desktop) build inventory > **Status (2026-10-05, P4-Z): resolved.** Win32 compat mode is off by default, and `dotnet build src/Files.App -f net10.0-desktop` reports diff --git a/docs/linux-port/spikes.md b/docs/linux-port/spikes.md index 9ea42471b5f5..afc4bcd03b1e 100644 --- a/docs/linux-port/spikes.md +++ b/docs/linux-port/spikes.md @@ -1,3 +1,5 @@ +> **Archived historical document.** This records an earlier plan or investigation, not current developer guidance. LinuxFiles is an independent Linux-only fork with no upstream sync or Windows support. See the [current policy](upstream-policy.md) and [developer guidance](../../AGENTS.md). + # Phase 0 Spikes A + B: Uno Platform host for Files.App.Controls Date: 2026-10-04 · Branch `linux/p0-uno-spike` (based on `linux/main` 09e42fcb4) · Host: Garuda Linux, KDE Plasma diff --git a/docs/linux-port/upstream-policy.md b/docs/linux-port/upstream-policy.md index 209636a4de45..5012bf7c6340 100644 --- a/docs/linux-port/upstream-policy.md +++ b/docs/linux-port/upstream-policy.md @@ -1,6 +1,6 @@ # Upstream policy -LinuxFiles is now an independent Linux fork of [Files](https://github.com/files-community/Files). `main` is the integration branch. We no longer merge upstream branches or run an automatic sync workflow. +LinuxFiles is now an independent Linux fork of [Files](https://github.com/files-community/Files). `main` is the integration branch. There is no upstream sync: we do not merge upstream branches or run an automatic sync workflow. Windows is no longer supported. The `upstream` remote for `files-community/Files` stays read-only: fetch and inspect its history, but never push to it, target it with pull requests, or post comments there as part of work on this fork. @@ -8,4 +8,4 @@ Bring over individual fixes selectively with `git cherry-pick -x `, on a Preserve `LICENSE-MIT`, `LICENSE-MPL`, `NOTICE.md`, `.github/NOTICE.md`, applicable file headers, and Files Community contributor credit. MIT notices continue to apply to inherited MIT code; MPL terms continue to apply to files bearing MPL headers. Independence does not change those licenses or imply endorsement by the Files Community. -Stage 1 removes the Windows leaf projects and their build references, Windows CI and MSIX packaging, and the former sync/pruning automation. Windows code inside `Files.App`, including `#if WINDOWS` branches, remains for later stages. +Windows leaf projects, Windows CI/MSIX packaging and the former sync/pruning automation have been removed. The Windows conditional blocks and `*.Windows.cs` files have also been removed. Remaining Windows-specific code is being deleted after checking for Linux consumers. Historical porting plans are archived context, not current build or maintenance instructions. diff --git a/src/Files.App.Controls/Files.App.Controls.csproj b/src/Files.App.Controls/Files.App.Controls.csproj index 1168176b1d76..4dddc0c13691 100644 --- a/src/Files.App.Controls/Files.App.Controls.csproj +++ b/src/Files.App.Controls/Files.App.Controls.csproj @@ -2,38 +2,22 @@ - $(WindowsTargetFramework);$(DesktopTargetFramework) + $(DesktopTargetFramework) enable Debug;Release x86;x64;arm64 true $(DefineConstants);OMNIBAR_DEBUG true - - true true false - - - $(MinimalWindowsVersion) - true - win-x86;win-x64;win-arm64 - - - - - - - - - - - - - $(WindowsTargetFramework) - $(MinimalWindowsVersion) - enable - true - Debug;Release - x86;x64;arm64 - win-x86;win-x64;win-arm64 - true - true - true - true - - - - - - - - - - - - diff --git a/src/Files.App.CsWin32/HRESULT.cs b/src/Files.App.CsWin32/HRESULT.cs deleted file mode 100644 index d05563ed5e7a..000000000000 --- a/src/Files.App.CsWin32/HRESULT.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace Windows.Win32.Foundation -{ - [DebuggerDisplay("{" + nameof(Value) + ",h}")] - public readonly partial struct HRESULT - { - /// - /// Throws an exception if the indicates a failure in debug mode. Otherwise, it returns the original . - /// - /// Returns the original value regardless of the operation's success. - public readonly HRESULT ThrowIfFailedOnDebug() - { -#if DEBUG - if (Failed) Marshal.ThrowExceptionForHR(Value); -#endif - - return this; - } - } -} diff --git a/src/Files.App.CsWin32/HStringStringMarshaller.cs b/src/Files.App.CsWin32/HStringStringMarshaller.cs deleted file mode 100644 index 84ece6831d61..000000000000 --- a/src/Files.App.CsWin32/HStringStringMarshaller.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32.Foundation; -using Windows.Win32.System.WinRT; - -namespace Windows.Win32; - -[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedIn, typeof(HStringStringMarshaller.ManagedToUnmanagedIn))] -[CustomMarshaller(typeof(string), MarshalMode.ManagedToUnmanagedOut, typeof(HStringStringMarshaller.ManagedToUnmanagedOut))] -[CustomMarshaller(typeof(string), MarshalMode.UnmanagedToManagedIn, typeof(HStringStringMarshaller.UnmanagedToManagedIn))] -[CustomMarshaller(typeof(string), MarshalMode.UnmanagedToManagedOut, typeof(HStringStringMarshaller.UnmanagedToManagedOut))] -internal static unsafe class HStringStringMarshaller -{ - public ref struct ManagedToUnmanagedIn - { - private nint _hstring; - - public void FromManaged(string? managed) - { - _hstring = CreateHString(managed); - } - - public nint ToUnmanaged() - => _hstring; - - public void Free() - { - DeleteHString(_hstring); - } - } - - public ref struct UnmanagedToManagedOut - { - private nint _hstring; - - public void FromManaged(string? managed) - { - _hstring = CreateHString(managed); - } - - public nint ToUnmanaged() - => _hstring; - - public void Free() - { - } - } - - public ref struct UnmanagedToManagedIn - { - private nint _hstring; - - public void FromUnmanaged(nint unmanaged) - { - _hstring = unmanaged; - } - - public string? ToManaged() - { - return ToManagedString(_hstring); - } - - public void Free() - { - } - } - - public ref struct ManagedToUnmanagedOut - { - private nint _hstring; - - public void FromUnmanaged(nint unmanaged) - { - _hstring = unmanaged; - } - - public string? ToManaged() - { - return ToManagedString(_hstring); - } - - public void Free() - { - DeleteHString(_hstring); - } - } - - private static nint CreateHString(string? managed) - { - if (managed is null) - return 0; - - HSTRING hstring; - fixed (char* sourceString = managed) - { - HRESULT hr = PInvoke.WindowsCreateString(new(sourceString), checked((uint)managed.Length), &hstring); - if (hr.Failed) - Marshal.ThrowExceptionForHR(hr.Value); - } - - return hstring; - } - - private static string? ToManagedString(nint hstring) - { - if (hstring == 0) - return null; - - uint length; - PCWSTR buffer = PInvoke.WindowsGetStringRawBuffer(new HSTRING(hstring), &length); - return new string((char*)buffer.Value, 0, checked((int)length)); - } - - private static void DeleteHString(nint hstring) - { - if (hstring != 0) - PInvoke.WindowsDeleteString(new HSTRING(hstring)); - } -} diff --git a/src/Files.App.CsWin32/IDetectionAndSharing.cs b/src/Files.App.CsWin32/IDetectionAndSharing.cs deleted file mode 100644 index ca0f3c0dc4ca..000000000000 --- a/src/Files.App.CsWin32/IDetectionAndSharing.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32.Foundation; - -namespace Windows.Win32.UI.Shell; - -[GeneratedComInterface, Guid("1FDA955C-61FF-11DA-978C-0008744FAAB7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -public partial interface IDetectionAndSharing -{ - [PreserveSig] - HRESULT GetStatus(DTSH_TYPE type, out DTSH_STATE state, out DTSH_ACTION action); - - [PreserveSig] - int TurnOn(nint hwnd, DTSH_TYPE type, int value); - - [PreserveSig] - int GetCurrentFwProfile(out /*NetFwProfileType2*/ int profile); - - [PreserveSig] - int GetStatusForProfile(/*NetFwProfileType2*/ int profile, DTSH_TYPE type, out DTSH_STATE state, out DTSH_ACTION action); - - [PreserveSig] - int TurnOnForProfile(nint hwnd, /*NetFwProfileType2*/ int profile, DTSH_TYPE type, int value); -} - -public enum DTSH_TYPE -{ - DTSH_NETWORK_DISCOVERY = 0, - DTSH_FILE_SHARING = 1, -} - -public enum DTSH_STATE -{ - DTSH_OFF = 0, - DTSH_ON = 1, -} - -public enum DTSH_ACTION -{ - DTSH_NONE = 0, -} diff --git a/src/Files.App.CsWin32/IOpenControlPanel.cs b/src/Files.App.CsWin32/IOpenControlPanel.cs deleted file mode 100644 index 72e9e33e7374..000000000000 --- a/src/Files.App.CsWin32/IOpenControlPanel.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32.Foundation; - -namespace Windows.Win32.UI.Shell; - -[GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16), Guid("D11AD862-66DE-4DF4-BF6C-1F5621996AF1"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -public unsafe partial interface IOpenControlPanel -{ - [PreserveSig] - HRESULT Open(PCWSTR name, PCWSTR page, void* site); - - [PreserveSig] - HRESULT GetPath(string name, nint path, uint pathLength); -} diff --git a/src/Files.App.CsWin32/IStorageProviderQuotaUI.cs b/src/Files.App.CsWin32/IStorageProviderQuotaUI.cs deleted file mode 100644 index b620d5123220..000000000000 --- a/src/Files.App.CsWin32/IStorageProviderQuotaUI.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32.Foundation; - -namespace Windows.Win32.System.WinRT -{ - [GeneratedComInterface, Guid("BA6295C3-312E-544F-9FD5-1F81B21F3649"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - public partial interface IStorageProviderQuotaUI - { - [PreserveSig] - HRESULT GetIids(out uint iidCount, out nint iids); - - [PreserveSig] - HRESULT GetRuntimeClassName([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] out string? className); - - [PreserveSig] - HRESULT GetTrustLevel(out TrustLevel trustLevel); - - [PreserveSig] - HRESULT GetQuotaTotalInBytes(out ulong value); - - [PreserveSig] - HRESULT PutQuotaTotalInBytes(ulong value); - - [PreserveSig] - HRESULT GetQuotaUsedInBytes(out ulong value); - - [PreserveSig] - HRESULT PutQuotaUsedInBytes(ulong value); - - [PreserveSig] - HRESULT GetQuotaUsedLabel([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] out string? value); - - [PreserveSig] - HRESULT PutQuotaUsedLabel([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] string? value); - - [PreserveSig] - HRESULT GetQuotaUsedColor(out nint value); - - [PreserveSig] - HRESULT PutQuotaUsedColor(nint value); - } -} diff --git a/src/Files.App.CsWin32/IStorageProviderStatusUI.cs b/src/Files.App.CsWin32/IStorageProviderStatusUI.cs deleted file mode 100644 index 6e4bc121c63f..000000000000 --- a/src/Files.App.CsWin32/IStorageProviderStatusUI.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Storage.Provider; -using Windows.Win32.Foundation; - -namespace Windows.Win32.System.WinRT; - -[GeneratedComInterface, Guid("D6B6A758-198D-5B80-977F-5FF73DA33118"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -public partial interface IStorageProviderStatusUI -{ - [PreserveSig] - HRESULT GetIids(out uint iidCount, out /* IID** */ nint iids); - - [PreserveSig] - HRESULT GetRuntimeClassName([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] out string? className); - - [PreserveSig] - HRESULT GetTrustLevel(out TrustLevel trustLevel); - - [PreserveSig] - HRESULT GetProviderState(out StorageProviderState value); - - [PreserveSig] - HRESULT PutProviderState(StorageProviderState value); - - [PreserveSig] - HRESULT GetProviderStateLabel([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] out string? value); - - [PreserveSig] - HRESULT PutProviderStateLabel([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] string? value); - - [PreserveSig] - HRESULT GetProviderStateIcon(out /* Windows.Foundation.Uri** */ nint value); - - [PreserveSig] - HRESULT PutProviderStateIcon(/* Windows.Foundation.Uri* */ nint value); - - [PreserveSig] - HRESULT GetSyncStatusCommand(out /* IStorageProviderUICommand** */ nint value); - - [PreserveSig] - HRESULT PutSyncStatusCommand(/* IStorageProviderUICommand* */ nint value); - - [PreserveSig] - HRESULT GetQuotaUI([MarshalAs(UnmanagedType.Interface)] out IStorageProviderQuotaUI value); - - [PreserveSig] - HRESULT PutQuotaUI([MarshalAs(UnmanagedType.Interface)] IStorageProviderQuotaUI value); - - [PreserveSig] - HRESULT GetMoreInfoUI(out /* IStorageProviderMoreInfoUI** */ nint value); - - [PreserveSig] - HRESULT PutMoreInfoUI(/* IStorageProviderMoreInfoUI* */ nint value); - - [PreserveSig] - HRESULT GetProviderPrimaryCommand(out /* IStorageProviderUICommand** */ nint value); - - [PreserveSig] - HRESULT PutProviderPrimaryCommand(/* IStorageProviderUICommand* */ nint value); - - [PreserveSig] - HRESULT GetProviderSecondaryCommands(out /* IVector** */ nint value); - - [PreserveSig] - HRESULT PutProviderSecondaryCommands(/* IVector* */ nint value); -} diff --git a/src/Files.App.CsWin32/IStorageProviderStatusUISource.cs b/src/Files.App.CsWin32/IStorageProviderStatusUISource.cs deleted file mode 100644 index 6af1b6677679..000000000000 --- a/src/Files.App.CsWin32/IStorageProviderStatusUISource.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32.Foundation; -using WinRT; - -namespace Windows.Win32.System.WinRT; - -[GeneratedComInterface, Guid("A306C249-3D66-5E70-9007-E43DF96051FF"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -public partial interface IStorageProviderStatusUISource -{ - [PreserveSig] - HRESULT GetIids(out uint iidCount, out /* IID** */ nint iids); - - [PreserveSig] - HRESULT GetRuntimeClassName([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] out string? className); - - [PreserveSig] - HRESULT GetTrustLevel(out TrustLevel trustLevel); - - [PreserveSig] - HRESULT GetStatusUI([MarshalAs(UnmanagedType.Interface)] out IStorageProviderStatusUI result); - - [PreserveSig] - HRESULT AddStatusUIChanged( - /* TypedEventHandler* */ nint handler, - out EventRegistrationToken token); - - [PreserveSig] - HRESULT RemoveStatusUIChanged(EventRegistrationToken token); -} diff --git a/src/Files.App.CsWin32/IStorageProviderStatusUISourceFactory.cs b/src/Files.App.CsWin32/IStorageProviderStatusUISourceFactory.cs deleted file mode 100644 index 6d7a1e1a5513..000000000000 --- a/src/Files.App.CsWin32/IStorageProviderStatusUISourceFactory.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32.Foundation; - -namespace Windows.Win32.System.WinRT; - -[GeneratedComInterface, Guid("12E46B74-4E5A-58D1-A62F-0376E8EE7DD8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -public partial interface IStorageProviderStatusUISourceFactory -{ - [PreserveSig] - HRESULT GetIids(out uint iidCount, out /* IID** */ nint iids); - - [PreserveSig] - HRESULT GetRuntimeClassName([MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] out string? className); - - [PreserveSig] - HRESULT GetTrustLevel(out TrustLevel trustLevel); - - [PreserveSig] - HRESULT GetStatusUISource( - [MarshalUsing(typeof(global::Windows.Win32.HStringStringMarshaller))] string? syncRootId, - [MarshalAs(UnmanagedType.Interface)] out IStorageProviderStatusUISource result); -} diff --git a/src/Files.App.CsWin32/ManualGuid.cs b/src/Files.App.CsWin32/ManualGuid.cs deleted file mode 100644 index 0927ba553eee..000000000000 --- a/src/Files.App.CsWin32/ManualGuid.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System; -using Windows.Win32.System.WinRT; - -namespace Windows.Win32 -{ - public static partial class CLSID - { - public static Guid CLSID_PinToFrequentExecute { get; } = new(0xB455F46Eu, 0xE4AF, 0x4035, 0xB0, 0xA4, 0xCF, 0x18, 0xD2, 0xF6, 0xF2, 0x8E); - public static Guid CLSID_UnPinFromFrequentExecute { get; } = new(0xEE20EEBAu, 0xDF64, 0x4A4E, 0xB7, 0xBB, 0x2D, 0x1C, 0x6B, 0x2D, 0xFC, 0xC1); - public static Guid CLSID_NewMenu { get; } = new(0xD969A300u, 0xE7FF, 0x11D0, 0xA9, 0x3B, 0x00, 0xA0, 0xC9, 0x0F, 0x27, 0x19); - public static Guid CLSID_OpenWithMenu { get; } = new(0x09799AFBu, 0xAD67, 0x11D1, 0xAB, 0xCD, 0x00, 0xC0, 0x4F, 0xC3, 0x09, 0x36); - public static Guid CLSID_DetectionAndSharing { get; } = new(0x1FDA955Bu, 0x61FF, 0x11DA, 0x97, 0x8C, 0x00, 0x08, 0x74, 0x4F, 0xAA, 0xB7); - public static Guid CLSID_OpenControlPanel { get; } = new(0x06622D85u, 0x6856, 0x4460, 0x8D, 0xE1, 0xA8, 0x19, 0x21, 0xB4, 0x1C, 0x4B); - } - - public static partial class FOLDERID - { - public static Guid FOLDERID_RecycleBinFolder { get; } = new(0xB7534046u, 0x3ECB, 0x4C18, 0xBE, 0x4E, 0x64, 0xCD, 0x4C, 0xB7, 0xD6, 0xAC); - public static Guid FOLDERID_ComputerFolder { get; } = new(0x0AC0837Cu, 0xBBF8, 0x452A, 0x85, 0x0D, 0x79, 0xD0, 0x8E, 0x66, 0x7C, 0xA7); - } -} diff --git a/src/Files.App.CsWin32/NativeMethods.json b/src/Files.App.CsWin32/NativeMethods.json deleted file mode 100644 index ac009d621b98..000000000000 --- a/src/Files.App.CsWin32/NativeMethods.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "$schema": "https://aka.ms/CsWin32.schema.json", - "allowMarshaling": true, - "public": true, - "comInterop": { - "useComSourceGenerators": true, - "preserveSigMethods": [ - "*" - ] - } -} diff --git a/src/Files.App.CsWin32/NativeMethods.txt b/src/Files.App.CsWin32/NativeMethods.txt deleted file mode 100644 index 83dfc995fa38..000000000000 --- a/src/Files.App.CsWin32/NativeMethods.txt +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -WNDPROC -WNDCLASSEXW -RegisterClassEx -CreateWindowEx -DestroyWindow -GetModuleHandle -RECT -NOTIFYICONIDENTIFIER -Shell_NotifyIconGetRect -RegisterWindowMessage -NOTIFYICONDATAW -Shell_NotifyIcon -GetCursorPos -ClientToScreen -DestroyMenu -AppendMenu -CreatePopupMenu -SetForegroundWindow -TrackPopupMenuEx -TRACK_POPUP_MENU_FLAGS -GetSystemMetricsForDpi -DefWindowProc -SYSTEM_METRICS_INDEX -GetDpiForWindow -HWND -LRESULT -WPARAM -LPARAM -WM_* -SetForegroundWindow -GetForegroundWindow -GetCurrentThreadId -GetWindowThreadProcessId -AttachThreadInput -SetWindowPos -SetFocus -SetActiveWindow -IsIconic -CopyFileFromApp -MoveFileFromApp -DeleteFileFromApp -RemoveDirectoryFromApp -GetKeyState -CreateDirectoryFromApp -WNetCancelConnection2 -NETRESOURCEW -WNetAddConnection3 -CREDENTIALW -CredWrite -WNetConnectionDialog1 -WNetGetConnection -CONNECTDLGSTRUCTW -RmRegisterResources -RmStartSession -RmEndSession -RmGetList -RM_UNIQUE_PROCESS -RM_PROCESS_INFO -CreateEvent -SetEvent -CancelIoEx -WaitForSingleObjectEx -ReadDirectoryChangesW -CreateFileFromAppW -GetFileAttributesExFromApp -SetFileAttributesFromApp -ReadFile -WriteFile -WriteFileEx -GetFileTime -SetFileTime -GetFileInformationByHandleEx -FILE_ID_BOTH_DIR_INFO -FSCTL_GET_REPARSE_POINT -IO_REPARSE_TAG_SYMLINK -FindFirstStreamW -FindNextStreamW -WIN32_FIND_STREAM_DATA -RegisterApplicationRestart -BROWSEINFOW -SHBrowseForFolder -SHGetPathFromIDList -SHGetKnownFolderIDList -SHChangeNotifyRegister -SHChangeNotifyDeregister -SHChangeNotification_Lock -SHChangeNotification_Unlock -SHChangeNotifyEntry -SHCNRF_SOURCE -SHCNE_ID -SHCreateStreamOnFileEx -DwmSetWindowAttribute -WIN32_ERROR -CoCreateInstance -FileOpenDialog -IFileOpenDialog -SHCreateItemFromParsingName -FileSaveDialog -IFileSaveDialog -D3D_DRIVER_TYPE -D3D_FEATURE_LEVEL -ID3D11Device -ID3D11DeviceContext -D3D11CreateDevice -IDXGIDevice -DCompositionCreateDevice -IDCompositionDevice -GetNamedSecurityInfo -ConvertSidToStringSid -ConvertStringSidToSid -SetNamedSecurityInfo -GetAclInformation -IsValidAcl -GetAce -SetEntriesInAcl -ACL_SIZE_INFORMATION -DeleteAce -ACCESS_ALLOWED_ACE -LookupAccountSid -GetComputerName -AddAccessAllowedAceEx -LocalAlloc -InitializeAcl -AddAce -LocalFree -IDesktopWallpaper -DesktopWallpaper -SHCreateShellItemArrayFromIDLists -ILCreateFromPath -CLSIDFromString -FindWindow -FindWindowEx -SendMessage -IsWindowVisible -COPYDATASTRUCT -WINDOW_LONG_PTR_INDEX -CallWindowProc -MINMAXINFO -SUBCLASSPROC -SetWindowPlacement -GetWindowPlacement -WINDOWPLACEMENT -GetSystemMetrics -MONITORENUMPROC -EnumDisplayMonitors -MONITORINFOEXW -GetMonitorInfo -CLASS_E_CLASSNOTAVAILABLE -E_INVALIDARG -RoInitialize -RoRegisterActivationFactories -RoRevokeActivationFactories -WindowsCreateString -WindowsDeleteString -IPreviewHandler -AssocQueryString -GetModuleHandle -LoadLibrary -FreeLibrary -LoadString -SHEmptyRecycleBin -SHFileOperation -SHGetFolderPath -SHGetKnownFolderPath -SHGFP_TYPE -SHGetKnownFolderItem -SHQUERYRBINFO -SHQueryRecycleBin -FileOperation -IFileOperation -IShellItem2 -PSGetPropertyKeyFromName -ShellExecuteEx -CoTaskMemFree -QueryDosDevice -DeviceIoControl -CreateFile -GetVolumeInformation -COMPRESSION_FORMAT -FILE_ACCESS_RIGHTS -FindFirstFileEx -FindNextFile -CreateFile -GetFileSizeEx -WIN32_FIND_DATAW -FILE_ACCESS_RIGHTS -SHAddToRecentDocs -SHARD -BHID_EnumItems -BHID_SFViewObject -IShellView -FOLDERID_RecycleBinFolder -CoTaskMemFree -SHGetIDListFromObject -SHCreateItemFromIDList -BHID_SFUIObject -IContextMenu -CMF_NORMAL -CMF_OPTIMIZEFORINVOKE -CMF_EXTENDEDVERBS -CMF_DEFAULTONLY -IApplicationDestinations -ApplicationDestinations -IApplicationDocumentLists -ApplicationDocumentLists -IApplicationActivationManager -MENU_ITEM_TYPE -COMPRESSION_FORMAT -FSCTL_SET_COMPRESSION -FSCTL_DISMOUNT_VOLUME -FSCTL_LOCK_VOLUME -FILE_FILE_COMPRESSION -WM_WINDOWPOSCHANGING -WINDOWPOS -UnregisterClass -E_POINTER -E_NOINTERFACE -E_FAIL -IShellFolder -FILE_FLAGS_AND_ATTRIBUTES -GetLogicalDrives -IShellItemImageFactory -GdipCreateBitmapFromHBITMAP -GdipGetImageEncodersSize -GdipGetImageEncoders -ImageFormatPNG -ImageFormatJPEG -IStream -CreateStreamOnHGlobal -STATFLAG -STREAM_SEEK -STGM -GdipSaveImageToStream -GdipGetImageRawFormat -_TRANSFER_SOURCE_FLAGS -E_NOTIMPL -DeleteObject -GdipDisposeImage -DeleteObject -OleInitialize -OleUninitialize -IShellIconOverlayManager -SHGetFileInfo -GetFileAttributes -SetFileAttributes -INVALID_FILE_ATTRIBUTES -SHDefExtractIconW -GdipCreateBitmapFromHICON -SHGetLocalizedName -SHLoadIndirectString -SHGetSetFolderCustomSettings -FCSM_ICONFILE -FCS_FORCEWRITE -IShellLinkW -SHFormatDrive -ITaskbarList -ITaskbarList2 -ITaskbarList3 -ITaskbarList4 -TaskbarList -ICustomDestinationList -DestinationList -IObjectArray -GetCurrentProcessExplicitAppUserModelID -SetCurrentProcessExplicitAppUserModelID -GdipCreateBitmapFromScan0 -BITMAP -GetObject -_SICHINTF -RoGetAgileReference -IQueryInfo -QITIPF_FLAGS -MapVirtualKey -S_FALSE -IExecuteCommand -IObjectWithSelection -SHCreateShellItemArrayFromShellItem -IDataObject -IShellExtInit -IContextMenu2 -GetSubMenu -GetMenuItemCount -GetMenuItemInfo -IsWow64Process2 -GetCurrentProcess -CertFreeCertificateContext -CryptMsgGetParam -CryptMsgClose -CryptMsgOpenToDecode -CryptMsgUpdate -CertOpenStore -CryptDecodeObject -CertFindCertificateInStore -CertComparePublicKeyInfo -CryptQueryObject -CertCloseStore -WinVerifyTrust -FileTimeToSystemTime -FileTimeToLocalFileTime -SystemTimeToFileTime -CMSG_SIGNER_INFO -CRYPT_ATTRIBUTE -FILETIME -CRYPT_BIT_BLOB -CERT_ALT_NAME_INFO -CERT_CONTEXT -CERT_INFO -CRYPT_ALGORITHM_IDENTIFIER -CERT_PUBLIC_KEY_INFO -CATALOG_INFO -WINTRUST_FILE_INFO -WINTRUST_DATA -HCERTSTORE -CERT_QUERY_ENCODING_TYPE -CertGetNameString -MessageBox -IDsObjectPicker -CLSID_DsObjectPicker -DSOP_* -DS_SELECTION_LIST -DVASPECT -CFSTR_DSOP_DS_SELECTION_LIST -GlobalLock -GlobalUnlock -RegisterClipboardFormat -ReleaseStgMedium -SafeArrayAccessData -SafeArrayUnaccessData -SafeArrayGetDim -SafeArrayGetLBound -SafeArrayGetUBound -IObjectWithSite -IPreviewHandlerVisuals -IPreviewHandlerFrame -IInitializeWithStream -IInitializeWithFile -IInitializeWithItem -WindowsGetStringRawBuffer -BHID_* -FileOperation -FileOpenDialog -FileSaveDialog -DesktopWallpaper -ApplicationActivationManager -CommandLineToArgvW -SHFILEINFOW -SHGFI_FLAGS -SHGetImageList -Windows.Win32.UI.Controls.IImageList -ExtractIconW -FindExecutableW -ILGetSize -ILFindLastID -ILIsParent -ILIsEqual -IShellItemArray -IEnumShellItems -ShellLink -SLR_FLAGS -SLGP_FLAGS -IShellLinkDataList -SHELL_LINK_DATA_FLAGS -IPersistFile -IUniformResourceLocatorW -IURL_SETURL_FLAGS -CLSID_InternetShortcut -ShellLibrary -IShellLibrary -LIBRARYFOLDERFILTER -DEFAULTSAVEFOLDERTYPE -LIBRARYOPTIONFLAGS -LIBRARYSAVEFLAGS -SHCreateDataObject -SHGetDesktopFolder -IDataObjectProvider -FILEGROUPDESCRIPTORW -DROPFILES -DragQueryFileW -PROPVARIANT -PropVariantClear -PSFormatForDisplayAlloc -FOLDERID_ControlPanelFolder -FOLDERID_NetHood -FOLDERID_Libraries -FOLDERID_ComputerFolder -COPYENGINE_E_RECYCLE_BIN_NOT_FOUND -COPYENGINE_E_USER_CANCELLED -COPYENGINE_S_DONT_PROCESS_CHILDREN -CMINVOKECOMMANDINFOEX -GCS_VERBW -OleGetClipboard -OleSetClipboard -OleFlushClipboard -GlobalAlloc -GlobalSize -OpenFileById -FILE_ID_DESCRIPTOR -GetFinalPathNameByHandleW -FILE_ID_INFO -FILE_STANDARD_INFO -ShellExecuteW -SBSP_SAMEBROWSER -SBSP_ABSOLUTE -K32EmptyWorkingSet -GetDoubleClickTime -SHChangeNotify diff --git a/src/Files.App.Storage/Files.App.Storage.csproj b/src/Files.App.Storage/Files.App.Storage.csproj index ab597cc47aea..8f19e2a4f590 100644 --- a/src/Files.App.Storage/Files.App.Storage.csproj +++ b/src/Files.App.Storage/Files.App.Storage.csproj @@ -3,8 +3,6 @@ $(DesktopTargetFramework) - - true true false enable @@ -22,36 +20,6 @@ - - - - - - - - - - ..\Files.App.CsWin32\bin\x64\$(Configuration)\$(WindowsTargetFramework)\Files.App.CsWin32.dll - - - - - - - - - - - - - - - - - - - - diff --git a/src/Files.App.Storage/Legacy/HomeFolder/HomeFolder.Windows.cs b/src/Files.App.Storage/Legacy/HomeFolder/HomeFolder.Windows.cs deleted file mode 100644 index 721dc33ebebb..000000000000 --- a/src/Files.App.Storage/Legacy/HomeFolder/HomeFolder.Windows.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Numerics; -using System.Runtime.CompilerServices; -using Windows.Win32; - -namespace Files.App.Storage.Storables -{ - public unsafe partial class HomeFolder : IHomeFolder - { - public string Id => "Home"; // Will be "files://Home" in the future. - - public string Name => "Home"; - - /// - public async IAsyncEnumerable GetItemsAsync(StorableType type = StorableType.Folder, [EnumeratorCancellation] CancellationToken cancellationToken = default) - { - await foreach (var folder in GetQuickAccessFolderAsync(cancellationToken)) - { - cancellationToken.ThrowIfCancellationRequested(); - - yield return folder; - } - - await foreach (var drive in GetLogicalDrivesAsync(cancellationToken)) - { - cancellationToken.ThrowIfCancellationRequested(); - - yield return drive; - } - - await foreach (var location in GetNetworkLocationsAsync(cancellationToken)) - { - cancellationToken.ThrowIfCancellationRequested(); - - yield return location; - } - } - - /// - public IAsyncEnumerable GetQuickAccessFolderAsync(CancellationToken cancellationToken = default) - { - IFolder folder = new WindowsFolder(new Guid("3936e9e4-d92c-4eee-a85a-bc16d5ea0819")); - return folder.GetItemsAsync(StorableType.Folder, cancellationToken); - } - - /// - public IAsyncEnumerable GetLogicalDrivesAsync(CancellationToken cancellationToken = default) - { - var availableDrives = PInvoke.GetLogicalDrives(); - if (availableDrives is 0) - return Enumerable.Empty().ToAsyncEnumerable(); - - int count = BitOperations.PopCount(availableDrives); - var driveLetters = new char[count]; - - count = 0; - char driveLetter = 'A'; - while (availableDrives is not 0) - { - if ((availableDrives & 1) is not 0) - driveLetters[count++] = driveLetter; - - availableDrives >>= 1; - driveLetter++; - } - - List driveItems = []; - foreach (char letter in driveLetters) - { - cancellationToken.ThrowIfCancellationRequested(); - - if (WindowsStorable.TryParse($"{letter}:\\") is not IWindowsStorable driveRoot) - throw new InvalidOperationException(); - - driveItems.Add(new WindowsFolder(driveRoot.ThisPtr)); - } - - return driveItems.ToAsyncEnumerable(); - } - - /// - public IAsyncEnumerable GetNetworkLocationsAsync(CancellationToken cancellationToken = default) - { - Guid FOLDERID_NetHood = new("{C5ABBF53-E17F-4121-8900-86626FC2C973}"); - IFolder folder = new WindowsFolder(FOLDERID_NetHood); - return folder.GetItemsAsync(StorableType.Folder, cancellationToken); - } - - /// - public IAsyncEnumerable GetRecentFilesAsync(CancellationToken cancellationToken = default) - { - Guid FOLDERID_NetHood = new("{AE50C081-EBD2-438A-8655-8A092E34987A}"); - IFolder folder = new WindowsFolder(FOLDERID_NetHood); - return folder.GetItemsAsync(StorableType.Folder, cancellationToken); - } - } -} diff --git a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs deleted file mode 100644 index e719cd6bb966..000000000000 --- a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Collections.Concurrent; -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Gdi; -using Windows.Win32.Graphics.GdiPlus; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Storage -{ - public static partial class WindowsStorableHelpers - { - // Fields - - private static (Guid Format, Guid Encorder)[]? GdiEncoders; - private static ConcurrentDictionary<(string, int, int), byte[]>? DllIconCache; - - // Methods - - /// - public static async Task GetThumbnailAsync(this IWindowsStorable storable, int size, SIIGBF options) - { - return await STATask.Run(() => - { - HRESULT hr = storable.TryGetThumbnail(size, options, out var thumbnailData).ThrowIfFailedOnDebug(); - return thumbnailData; - }, null); - } - - /// - /// Retrieves a thumbnail image data for the specified using . - /// - /// An object that implements and represents a shell item on Windows. - /// The desired size (in pixels) of the thumbnail (width and height are equal). - /// A combination of flags that specify how the thumbnail should be retrieved. - /// A byte array containing the thumbnail image in its native format (e.g., PNG, JPEG). - /// If the thumbnail is JPEG, this tries to decoded as a PNG instead because JPEG loses data. - public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int size, SIIGBF options, out byte[]? thumbnailData) - { - thumbnailData = null; - - if (storable.ThisPtr is not IShellItemImageFactory pShellItemImageFactory) - return HRESULT.E_NOINTERFACE; - - HBITMAP hBitmap = default; - try - { - // Get HBITMAP - HRESULT hr = pShellItemImageFactory.GetImage(new(size, size), options, &hBitmap); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - // Retrieve BITMAP data - BITMAP bmp = default; - if (PInvoke.GetObject(hBitmap, sizeof(BITMAP), &bmp) is 0) - return HRESULT.E_FAIL; - - // Allocate buffer for flipped pixel data - byte* flippedBits = (byte*)NativeMemory.AllocZeroed((nuint)(bmp.bmWidthBytes * bmp.bmHeight)); - try - { - // Flip the image manually row by row - for (int y = 0; y < bmp.bmHeight; y++) - { - Buffer.MemoryCopy( - (byte*)bmp.bmBits + y * bmp.bmWidthBytes, - flippedBits + (bmp.bmHeight - y - 1) * bmp.bmWidthBytes, - bmp.bmWidthBytes, - bmp.bmWidthBytes); - } - - // Create GpBitmap from the flipped pixel data - GpBitmap* gpBitmap = default; - if (PInvoke.GdipCreateBitmapFromScan0(bmp.bmWidth, bmp.bmHeight, bmp.bmWidthBytes, PInvoke.PixelFormat32bppARGB, flippedBits, &gpBitmap) != Status.Ok) - { - if (gpBitmap is not null) PInvoke.GdipDisposeImage((GpImage*)gpBitmap); - return HRESULT.E_FAIL; - } - - return TryConvertGpBitmapToByteArray(gpBitmap, out thumbnailData) - ? HRESULT.S_OK - : HRESULT.E_FAIL; - } - finally - { - NativeMemory.Free(flippedBits); - } - } - finally - { - if (!hBitmap.IsNull) PInvoke.DeleteObject(hBitmap); - } - } - - public unsafe static HRESULT TryExtractImageFromDll(this IWindowsStorable storable, int size, int index, out byte[]? imageData) - { - DllIconCache ??= []; - imageData = null; - - if (storable.ToString() is not { } path) - return HRESULT.E_INVALIDARG; - - if (DllIconCache.TryGetValue((path, index, size), out var cachedImageData)) - { - imageData = cachedImageData; - return HRESULT.S_OK; - } - else - { - HICON hIcon = default; - HRESULT hr = default; - - fixed (char* pszPath = path) - hr = PInvoke.SHDefExtractIcon(pszPath, -1 * index, 0, &hIcon, null, (uint)size); - - try - { - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - // Convert to GpBitmap of GDI+ - GpBitmap* gpBitmap = default; - if (PInvoke.GdipCreateBitmapFromHICON(hIcon, &gpBitmap) is not Status.Ok) - { - if (gpBitmap is not null) PInvoke.GdipDisposeImage((GpImage*)gpBitmap); - return HRESULT.E_FAIL; - } - - if (!TryConvertGpBitmapToByteArray(gpBitmap, out imageData) || imageData is null) - return HRESULT.E_FAIL; - - DllIconCache[(path, index, size)] = imageData; - - return HRESULT.S_OK; - } - finally - { - if (!hIcon.IsNull) PInvoke.DestroyIcon(hIcon); - } - } - } - - public unsafe static bool TryConvertGpBitmapToByteArray(GpBitmap* gpBitmap, out byte[]? imageData) - { - imageData = null; - if (gpBitmap is null) - return false; - - try - { - // Get an encoder for PNG - Guid format = Guid.Empty; - if (PInvoke.GdipGetImageRawFormat((GpImage*)gpBitmap, &format) is not Status.Ok) - return false; - - Guid encoder = GetEncoderClsid(format); - if (format == PInvoke.ImageFormatJPEG || encoder == Guid.Empty) - { - format = PInvoke.ImageFormatPNG; - encoder = GetEncoderClsid(format); - } - - HRESULT hr = PInvoke.CreateStreamOnHGlobal(HGLOBAL.Null, true, out IStream pStream); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - if (PInvoke.GdipSaveImageToStream((GpImage*)gpBitmap, pStream, &encoder, (EncoderParameters*)null) is not Status.Ok) - return false; - - STATSTG stat = default; - hr = pStream.Stat(out stat, STATFLAG.STATFLAG_NONAME); - if (hr.ThrowIfFailedOnDebug().Failed || stat.cbSize > int.MaxValue) - return false; - - var statSize = (int)stat.cbSize; - byte* rawThumbnailData = (byte*)NativeMemory.Alloc((nuint)statSize); - - try - { - pStream.Seek(0L, System.IO.SeekOrigin.Begin); - hr = pStream.Read(rawThumbnailData, (uint)statSize); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - imageData = new ReadOnlySpan(rawThumbnailData, statSize).ToArray(); - return true; - } - finally - { - NativeMemory.Free(rawThumbnailData); - } - } - finally - { - PInvoke.GdipDisposeImage((GpImage*)gpBitmap); - } - - Guid GetEncoderClsid(Guid format) - { - foreach ((Guid Format, Guid Encoder) in GetGdiEncoders()) - if (Format == format) - return Encoder; - - return Guid.Empty; - } - - (Guid Format, Guid Encorder)[] GetGdiEncoders() - { - if (GdiEncoders is not null) - return GdiEncoders; - - if (PInvoke.GdipGetImageEncodersSize(out var numEncoders, out var size) is not Status.Ok) - return []; - - ImageCodecInfo* pImageCodecInfo = (ImageCodecInfo*)NativeMemory.Alloc(size); - try - { - if (PInvoke.GdipGetImageEncoders(numEncoders, size, pImageCodecInfo) is not Status.Ok) - return []; - - ReadOnlySpan codecs = new(pImageCodecInfo, (int)numEncoders); - var encoders = new (Guid Format, Guid Encoder)[codecs.Length]; - for (int index = 0; index < codecs.Length; index++) - encoders[index] = (codecs[index].FormatID, codecs[index].Clsid); - - return GdiEncoders = encoders; - } - finally - { - NativeMemory.Free(pImageCodecInfo); - } - } - } - - public unsafe static HRESULT TrySetFolderIcon(this IWindowsStorable storable, IWindowsStorable iconFile, int index) - { - if (storable.GetDisplayName() is not { } folderPath || - iconFile.GetDisplayName() is not { } filePath) - return HRESULT.E_INVALIDARG; - - fixed (char* pszFolderPath = folderPath, pszIconFile = filePath) - { - SHFOLDERCUSTOMSETTINGS settings = default; - settings.dwSize = (uint)sizeof(SHFOLDERCUSTOMSETTINGS); - settings.dwMask = PInvoke.FCSM_ICONFILE; - settings.pszIconFile = pszIconFile; - settings.cchIconFile = 0; - settings.iIconIndex = index; - - HRESULT hr = PInvoke.SHGetSetFolderCustomSettings(&settings, pszFolderPath, PInvoke.FCS_FORCEWRITE); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - } - - return HRESULT.S_OK; - } - - public unsafe static HRESULT TrySetShortcutIcon(this IWindowsStorable storable, IWindowsStorable iconFile, int index) - { - if (iconFile.ToString() is not { } iconFilePath) - return HRESULT.E_INVALIDARG; - - HRESULT hr = storable.ThisPtr.BindToHandler(null, PInvoke.BHID_SFUIObject, out IShellLinkW? pShellLink); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - fixed (char* pszIconFilePath = iconFilePath) - hr = pShellLink!.SetIconLocation(iconFilePath, index); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - return HRESULT.S_OK; - } - } -} diff --git a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.PowerShell.cs b/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.PowerShell.cs deleted file mode 100644 index bbc8dcbf34cb..000000000000 --- a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.PowerShell.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -namespace Files.App.Storage -{ - public static partial class WindowsStorableHelpers - { - public static async Task TrySetShortcutIconOnPowerShellAsElevatedAsync(this IWindowsStorable storable, IWindowsStorable iconFile, int index) - { - static string ToPowerShellStringLiteral(string value) - => $"'{value.Replace("'", "''", StringComparison.Ordinal)}'"; - - var filePath = storable.ToString(); - var iconPath = iconFile.ToString(); - if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(iconPath)) - return false; - - string psScript = - $@"$FilePath = {ToPowerShellStringLiteral(filePath)} - $IconFile = {ToPowerShellStringLiteral(iconPath)} - $IconIndex = '{index}' - - $Shell = New-Object -ComObject WScript.Shell - $Shortcut = $Shell.CreateShortcut($FilePath) - $Shortcut.IconLocation = ""$IconFile, $IconIndex"" - $Shortcut.Save()"; - - var process = new Process() - { - StartInfo = new ProcessStartInfo() - { - FileName = "PowerShell.exe", - Arguments = $"-NoProfile -EncodedCommand {Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(psScript))}", - Verb = "RunAs", - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - UseShellExecute = true - }, - }; - - process.Start(); - await process.WaitForExitAsync(); - - return true; - } - } -} diff --git a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Process.cs b/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Process.cs deleted file mode 100644 index dc86b2acb980..000000000000 --- a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Process.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32; -using Windows.Win32.System.SystemInformation; - -namespace Files.App.Storage -{ - public unsafe static partial class WindowsStorableHelpers - { - public static bool IsOnArmProcessor() - { - IMAGE_FILE_MACHINE dwMachineType = default; - - // Assumes the current process token has "PROCESS_QUERY_INFORMATION" or "PROCESS_QUERY_LIMITED_INFORMATION" access right - bool fResult = PInvoke.IsWow64Process2(PInvoke.GetCurrentProcess(), null, &dwMachineType); - if (!fResult) - Debug.WriteLine($"{nameof(PInvoke.IsWow64Process2)} has failed."); - - return dwMachineType is - IMAGE_FILE_MACHINE.IMAGE_FILE_MACHINE_THUMB or - IMAGE_FILE_MACHINE.IMAGE_FILE_MACHINE_ARMNT or - IMAGE_FILE_MACHINE.IMAGE_FILE_MACHINE_ARM64 or - IMAGE_FILE_MACHINE.IMAGE_FILE_MACHINE_ARM; - } - } -} diff --git a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Shell.cs b/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Shell.cs deleted file mode 100644 index e667b5024590..000000000000 --- a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Shell.cs +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Text; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.System.SystemServices; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; -using Windows.Win32.UI.Shell.PropertiesSystem; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Storage -{ - public unsafe static partial class WindowsStorableHelpers - { - public static HRESULT GetPropertyValue(this IWindowsStorable storable, string propKey, out TValue value) - { - if (storable.ThisPtr is not IShellItem2 pShellItem2) - { - value = default!; - return HRESULT.E_NOINTERFACE; - } - - HRESULT hr = PInvoke.PSGetPropertyKeyFromName(propKey, out PROPERTYKEY propertyKey); - if (hr.ThrowIfFailedOnDebug().Failed) - { - value = default!; - return hr; - } - - if (typeof(TValue) == typeof(string)) - { - hr = pShellItem2.GetString(propertyKey, out PWSTR szPropertyValue); - value = (TValue)(object)szPropertyValue.ToString(); - PInvoke.CoTaskMemFree(szPropertyValue); - - return hr; - } - if (typeof(TValue) == typeof(bool)) - { - hr = pShellItem2.GetBool(propertyKey, out BOOL fPropertyValue); - bool propertyValue = fPropertyValue; - value = Unsafe.As(ref propertyValue); - - return hr; - } - else - { - value = default!; - return HRESULT.E_FAIL; - } - } - - public static bool HasShellAttributes(this IWindowsStorable storable, SFGAO_FLAGS attributes) - { - return storable.ThisPtr.GetAttributes(attributes, out var dwRetAttributes).Succeeded && dwRetAttributes == attributes; - } - - public static string GetDisplayName(this IWindowsStorable storable, SIGDN options = SIGDN.SIGDN_FILESYSPATH) - { - HRESULT hr = storable.ThisPtr.GetDisplayName(options, out PWSTR pszName); - string name = hr.ThrowIfFailedOnDebug().Succeeded - ? pszName.ToString() - : string.Empty; - PInvoke.CoTaskMemFree(pszName); - - return name; - } - - public static HRESULT TryInvokeContextMenuVerb(this IWindowsStorable storable, string verbName) - { - Debug.Assert(Thread.CurrentThread.GetApartmentState() is ApartmentState.STA); - - HRESULT hr = storable.ThisPtr.BindToHandler(null, PInvoke.BHID_SFUIObject, out IContextMenu? pContextMenu); - if (hr.ThrowIfFailedOnDebug().Failed || pContextMenu is null) - return hr; - - HMENU hMenu = PInvoke.CreatePopupMenu(); - hr = pContextMenu.QueryContextMenu(hMenu, 0, 1, 0x7FFF, PInvoke.CMF_OPTIMIZEFORINVOKE); - - CMINVOKECOMMANDINFO cmici = default; - cmici.cbSize = (uint)sizeof(CMINVOKECOMMANDINFO); - cmici.nShow = (int)SHOW_WINDOW_CMD.SW_HIDE; - - fixed (byte* pszVerbName = Encoding.ASCII.GetBytes(verbName)) - { - cmici.lpVerb = new(pszVerbName); - hr = pContextMenu.InvokeCommand(cmici); - - if (!PInvoke.DestroyMenu(hMenu)) - return HRESULT.E_FAIL; - - return hr; - } - } - - public static HRESULT TryInvokeContextMenuVerbs(this IWindowsStorable storable, string[] verbNames, bool earlyReturnOnSuccess) - { - Debug.Assert(Thread.CurrentThread.GetApartmentState() is ApartmentState.STA); - - HRESULT hr = storable.ThisPtr.BindToHandler(null, PInvoke.BHID_SFUIObject, out IContextMenu? pContextMenu); - if (hr.ThrowIfFailedOnDebug().Failed || pContextMenu is null) - return hr; - - HMENU hMenu = PInvoke.CreatePopupMenu(); - HRESULT result = HRESULT.S_OK; - try - { - hr = pContextMenu.QueryContextMenu(hMenu, 0, 1, 0x7FFF, PInvoke.CMF_OPTIMIZEFORINVOKE); - result = hr; - - CMINVOKECOMMANDINFO cmici = default; - cmici.cbSize = (uint)sizeof(CMINVOKECOMMANDINFO); - cmici.nShow = (int)SHOW_WINDOW_CMD.SW_HIDE; - - foreach (var verbName in verbNames) - { - fixed (byte* pszVerbName = Encoding.ASCII.GetBytes(verbName)) - { - cmici.lpVerb = new(pszVerbName); - hr = pContextMenu.InvokeCommand(cmici); - result = hr; - - if (hr.Succeeded && earlyReturnOnSuccess) - break; - } - } - } - finally - { - if (!PInvoke.DestroyMenu(hMenu)) - result = HRESULT.E_FAIL; - } - - return result; - } - - public static HRESULT TryGetShellTooltip(this IWindowsStorable storable, out string? tooltip) - { - tooltip = null; - - HRESULT hr = storable.ThisPtr.BindToHandler(null, PInvoke.BHID_SFUIObject, out IQueryInfo? pQueryInfo); - if (hr.ThrowIfFailedOnDebug().Failed || pQueryInfo is null) - return hr; - - hr = pQueryInfo.GetInfoTip(QITIPF_FLAGS.QITIPF_DEFAULT, out var pszTip); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - tooltip = pszTip.ToString(); - PInvoke.CoTaskMemFree(pszTip); - - return HRESULT.S_OK; - } - - public static HRESULT TryPinFolderToQuickAccess(this IWindowsFolder @this) - { - HRESULT hr = default; - - hr = PInvoke.CoCreateInstance(CLSID.CLSID_PinToFrequentExecute, null, CLSCTX.CLSCTX_INPROC_SERVER, out IExecuteCommand? pExecuteCommand); - if (hr.ThrowIfFailedOnDebug().Failed || pExecuteCommand is null) - return hr; - - hr = PInvoke.SHCreateShellItemArrayFromShellItem(@this.ThisPtr, out IShellItemArray pShellItemArray); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - if (pExecuteCommand is not IObjectWithSelection pObjectWithSelection) - return HRESULT.E_NOINTERFACE; - - hr = pObjectWithSelection.SetSelection(pShellItemArray); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - hr = pExecuteCommand.Execute(); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - return HRESULT.S_OK; - } - - public static HRESULT TryUnpinFolderFromQuickAccess(this IWindowsFolder @this) - { - HRESULT hr = default; - - hr = PInvoke.CoCreateInstance(CLSID.CLSID_UnPinFromFrequentExecute, null, CLSCTX.CLSCTX_INPROC_SERVER, out IExecuteCommand? pExecuteCommand); - if (hr.ThrowIfFailedOnDebug().Failed || pExecuteCommand is null) - return hr; - - hr = PInvoke.SHCreateShellItemArrayFromShellItem(@this.ThisPtr, out IShellItemArray pShellItemArray); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - if (pExecuteCommand is not IObjectWithSelection pObjectWithSelection) - return HRESULT.E_NOINTERFACE; - - hr = pObjectWithSelection.SetSelection(pShellItemArray); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - hr = pExecuteCommand.Execute(); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - return HRESULT.S_OK; - } - - public static IEnumerable GetShellNewItems(this IWindowsFolder @this) - { - HRESULT hr = default; - - hr = PInvoke.CoCreateInstance(CLSID.CLSID_NewMenu, null, CLSCTX.CLSCTX_INPROC_SERVER, out IContextMenu? pNewMenu); - if (hr.ThrowIfFailedOnDebug().Failed || pNewMenu is null) - return []; - - if (pNewMenu is not IContextMenu2 pContextMenu2 || - pNewMenu is not IShellExtInit pShellExtInit) - return []; - - @this.ShellNewMenu = pNewMenu; - - hr = PInvoke.SHGetIDListFromObject(@this.ThisPtr, out ITEMIDLIST* pFolderPidl); - if (hr.ThrowIfFailedOnDebug().Failed) - return []; - - hr = pShellExtInit.Initialize(pFolderPidl, null!, default); - if (hr.ThrowIfFailedOnDebug().Failed) - return []; - - // Inserts "New (&W)" - HMENU hMenu = PInvoke.CreatePopupMenu(); - hr = pNewMenu.QueryContextMenu(hMenu, 0, 1, 256, 0); - if (hr.ThrowIfFailedOnDebug().Failed) - return []; - - // Invokes CNewMenu::_InitMenuPopup(), which populates the hSubMenu - HMENU hSubMenu = PInvoke.GetSubMenu(hMenu, 0); - hr = pContextMenu2.HandleMenuMsg(PInvoke.WM_INITMENUPOPUP, (WPARAM)(nuint)hSubMenu.Value, 0); - if (hr.ThrowIfFailedOnDebug().Failed) - return []; - - uint dwCount = unchecked((uint)PInvoke.GetMenuItemCount(hSubMenu)); - if (dwCount is unchecked((uint)-1)) - return []; - - // Enumerates and populates the list - List shellNewItems = []; - for (uint dwIndex = 0; dwIndex < dwCount; dwIndex++) - { - MENUITEMINFOW mii = default; - mii.cbSize = (uint)sizeof(MENUITEMINFOW); - mii.fMask = MENU_ITEM_MASK.MIIM_STRING | MENU_ITEM_MASK.MIIM_ID | MENU_ITEM_MASK.MIIM_STATE; - mii.dwTypeData = (char*)NativeMemory.Alloc(256U); - mii.cch = 256; - - if (PInvoke.GetMenuItemInfo(hSubMenu, dwIndex, true, &mii)) - { - shellNewItems.Add(new() - { - Id = mii.wID, - Name = mii.dwTypeData.ToString(), - Type = (WindowsContextMenuType)mii.fState, - }); - } - - NativeMemory.Free(mii.dwTypeData); - } - - return shellNewItems; - } - - public static bool InvokeShellNewItem(this IWindowsFolder @this, WindowsContextMenuItem item) - { - HRESULT hr = default; - - if (@this.ShellNewMenu is null) - { - hr = PInvoke.CoCreateInstance(CLSID.CLSID_NewMenu, null, CLSCTX.CLSCTX_INPROC_SERVER, out IContextMenu? pNewMenu); - if (hr.ThrowIfFailedOnDebug().Failed || pNewMenu is null) - return false; - - @this.ShellNewMenu = pNewMenu; - } - - CMINVOKECOMMANDINFO cmici = default; - cmici.cbSize = (uint)sizeof(CMINVOKECOMMANDINFO); - cmici.lpVerb = (PCSTR)(byte*)item.Id; - cmici.nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL; - - hr = @this.ShellNewMenu.InvokeCommand(cmici); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - return false; - } - } -} diff --git a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Storage.cs b/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Storage.cs deleted file mode 100644 index 49188f617d38..000000000000 --- a/src/Files.App.Storage/Windows/Helpers/WindowsStorableHelpers.Storage.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - public unsafe static partial class WindowsStorableHelpers - { - public static bool TryGetFileAttributes(this IWindowsStorable storable, out FILE_FLAGS_AND_ATTRIBUTES attributes) - { - attributes = (FILE_FLAGS_AND_ATTRIBUTES)PInvoke.GetFileAttributes(storable.GetDisplayName()); - - if ((uint)attributes is PInvoke.INVALID_FILE_ATTRIBUTES) - { - attributes = 0; - return false; - } - else - { - return true; - } - } - - public static bool TrySetFileAttributes(this IWindowsStorable storable, FILE_FLAGS_AND_ATTRIBUTES attributes) - { - if (attributes is FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_COMPRESSED) - return storable.TryToggleFileCompressedAttribute(true); - - if (!storable.TryGetFileAttributes(out var previousAttributes)) - return false; - return PInvoke.SetFileAttributes(storable.GetDisplayName(), previousAttributes | attributes); - } - - public static bool TryUnsetFileAttributes(this IWindowsStorable storable, FILE_FLAGS_AND_ATTRIBUTES attributes) - { - if (attributes is FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_COMPRESSED) - return storable.TryToggleFileCompressedAttribute(false); - - if (!storable.TryGetFileAttributes(out var previousAttributes)) - return false; - return PInvoke.SetFileAttributes(storable.GetDisplayName(), previousAttributes & ~attributes); - } - - public static bool TryToggleFileCompressedAttribute(this IWindowsStorable storable, bool value) - { - // GENERIC_READ | GENERIC_WRITE flags are needed here - // FILE_FLAG_BACKUP_SEMANTICS is used to open directories - using var hFile = PInvoke.CreateFile( - storable.GetDisplayName(), - (uint)(FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE | FILE_ACCESS_RIGHTS.FILE_WRITE_ATTRIBUTES), - FILE_SHARE_MODE.FILE_SHARE_READ | FILE_SHARE_MODE.FILE_SHARE_WRITE, - lpSecurityAttributes: null, - FILE_CREATION_DISPOSITION.OPEN_EXISTING, - FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_NORMAL | FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, - hTemplateFile: null); - - if (hFile.IsInvalid) - return false; - - var bytesReturned = 0u; - var compressionFormat = value - ? COMPRESSION_FORMAT.COMPRESSION_FORMAT_DEFAULT - : COMPRESSION_FORMAT.COMPRESSION_FORMAT_NONE; - - var result = PInvoke.DeviceIoControl( - new(hFile.DangerousGetHandle()), - PInvoke.FSCTL_SET_COMPRESSION, - &compressionFormat, - sizeof(ushort), - null, - 0u, - &bytesReturned); - - return result; - } - - public static bool TryShowFormatDriveDialog(HWND hWnd, uint driveLetterIndex, SHFMT_ID id, SHFMT_OPT options) - { - // NOTE: This calls an undocumented elevatable COM class, shell32.dll!CFormatEngine so this doesn't need to be elevated beforehand. - var result = PInvoke.SHFormatDrive(hWnd, driveLetterIndex, id, options); - return result is 0xFFFF; - } - - public static bool TryRenameVolumeLabel(string path, string newLabel) - { - // TODO: Use shell32.dll!CMountPointRename (CLSID: 60173D16-A550-47f0-A14B-C6F9E4DA0831, IID: 92F8D886-AB61-4113-BD4F-2E894397386F) - - return false; - } - } -} diff --git a/src/Files.App.Storage/Windows/IWindowsFile.cs b/src/Files.App.Storage/Windows/IWindowsFile.cs deleted file mode 100644 index 43f30155f907..000000000000 --- a/src/Files.App.Storage/Windows/IWindowsFile.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Storage -{ - public interface IWindowsFile : IWindowsStorable, IChildFile - { - } -} diff --git a/src/Files.App.Storage/Windows/IWindowsFolder.cs b/src/Files.App.Storage/Windows/IWindowsFolder.cs deleted file mode 100644 index 99116eb9da47..000000000000 --- a/src/Files.App.Storage/Windows/IWindowsFolder.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - public interface IWindowsFolder : IWindowsStorable, IChildFolder - { - /// - /// Gets or sets the cached for the ShellNew context menu. - /// - public IContextMenu? ShellNewMenu { get; set; } - } -} diff --git a/src/Files.App.Storage/Windows/IWindowsStorable.cs b/src/Files.App.Storage/Windows/IWindowsStorable.cs deleted file mode 100644 index de5396473e60..000000000000 --- a/src/Files.App.Storage/Windows/IWindowsStorable.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - public interface IWindowsStorable : IStorableChild, IEquatable, IDisposable - { - IShellItem ThisPtr { get; set; } - - IContextMenu? ContextMenu { get; set; } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/JumpListDestinationType.cs b/src/Files.App.Storage/Windows/Managers/JumpListDestinationType.cs deleted file mode 100644 index b811e47d0625..000000000000 --- a/src/Files.App.Storage/Windows/Managers/JumpListDestinationType.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Files.App.Storage -{ - public enum JumpListDestinationType - { - Pinned, - - Recent, - - Frequent, - } -} diff --git a/src/Files.App.Storage/Windows/Managers/JumpListItem.cs b/src/Files.App.Storage/Windows/Managers/JumpListItem.cs deleted file mode 100644 index ff20f2229405..000000000000 --- a/src/Files.App.Storage/Windows/Managers/JumpListItem.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Storage -{ - public partial class JumpListItem - { - - } -} diff --git a/src/Files.App.Storage/Windows/Managers/JumpListItemType.cs b/src/Files.App.Storage/Windows/Managers/JumpListItemType.cs deleted file mode 100644 index 4fa801b68154..000000000000 --- a/src/Files.App.Storage/Windows/Managers/JumpListItemType.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Storage -{ - public enum JumpListItemType - { - Item, - - Separator, - } -} diff --git a/src/Files.App.Storage/Windows/Managers/JumpListManager.cs b/src/Files.App.Storage/Windows/Managers/JumpListManager.cs deleted file mode 100644 index 80e00a830757..000000000000 --- a/src/Files.App.Storage/Windows/Managers/JumpListManager.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -namespace Files.App.Storage -{ - public unsafe class JumpListManager : IDisposable - { - public string AppId { get; } - - public JumpListManager(string appId) - { - if (string.IsNullOrEmpty(appId)) - throw new ArgumentException("App ID cannot be null or empty.", nameof(appId)); - - AppId = appId; - //_jumpList = new ConcurrentDictionary(); - } - - public IEnumerable GetAutomaticDestinations() - { - return []; - } - - public IEnumerable GetCustomDestinations() - { - return []; - } - - public void Dispose() - { - } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/STATask.cs b/src/Files.App.Storage/Windows/Managers/STATask.cs deleted file mode 100644 index c8e2791f9ede..000000000000 --- a/src/Files.App.Storage/Windows/Managers/STATask.cs +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Microsoft.Extensions.Logging; -using System.Collections.Concurrent; -using System.Runtime.ExceptionServices; -using System.Threading.Channels; -using Windows.Win32; - -namespace Files.App.Storage -{ - /// - /// Represents a work scheduled to execute on a STA thread. - /// - public partial class STATask - { - private const int PooledThreadCount = 12; - - private static readonly Channel _pooledQueue = Channel.CreateUnbounded(); - private static bool _poolStarted; - - /// - /// Schedules the specified work on a shared pool of persistent STA threads, avoiding per-call thread creation. - /// - /// The type of the result returned by the function. - /// The work to execute on an STA pool thread. - /// A logger to capture any exception that occurs during execution. - /// A that represents the scheduled work. - public static Task RunPooled(Func func, ILogger? logger) - { - if (!Interlocked.CompareExchange(ref _poolStarted, true, false)) - { - for (int i = 0; i < PooledThreadCount; i++) - { - Thread thread = - new(() => - { - PInvoke.OleInitialize(); - - // Consume synchronously: awaiting here would resume on an MTA thread pool thread, losing the STA apartment - var reader = _pooledQueue.Reader; - while (reader.WaitToReadAsync().AsTask().GetAwaiter().GetResult()) - while (reader.TryRead(out var work)) - work(); - }); - - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Name = $"STATask pool {i}"; - thread.Start(); - } - } - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - _pooledQueue.Writer.TryWrite(() => - { - try - { - tcs.SetResult(func()); - } - catch (Exception ex) - { - tcs.SetResult(default!); - logger?.LogWarning(ex, "An exception was occurred during the execution within STA."); - } - }); - - return tcs.Task; - } - - /// - /// Schedules the specified work to execute in a new background thread initialized with STA state. - /// - /// The work to execute in the STA thread. - /// A logger to capture any exception that occurs during execution. - /// A that represents the work scheduled to execute in the STA thread. - public static Task Run(Action action, ILogger? logger) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - Thread thread = - new(() => - { - PInvoke.OleInitialize(); - - try - { - action(); - tcs.SetResult(); - } - catch (Exception ex) - { - tcs.SetResult(); - logger?.LogWarning(ex, "An exception was occurred during the execution within STA."); - } - finally - { - PInvoke.OleUninitialize(); - } - }); - - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - - return tcs.Task; - } - - /// - /// Schedules the specified work to execute in a new background thread initialized with STA state. - /// - /// The type of the result returned by the function. - /// The work to execute in the STA thread. - /// A logger to capture any exception that occurs during execution. - /// A that represents the work scheduled to execute in the STA thread. - public static Task Run(Func func, ILogger? logger) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - Thread thread = - new(() => - { - PInvoke.OleInitialize(); - - try - { - tcs.SetResult(func()); - } - catch (Exception ex) - { - tcs.SetResult(default!); - logger?.LogWarning(ex, "An exception was occurred during the execution within STA."); - } - finally - { - PInvoke.OleUninitialize(); - } - }); - - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - - return tcs.Task; - } - - /// - /// Schedules the specified work to execute in a new background thread initialized with STA state. - /// - /// The work to execute in the STA thread. - /// A logger to capture any exception that occurs during execution. - /// A that represents the work scheduled to execute in the STA thread. - public static Task Run(Func func, ILogger? logger) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - Thread thread = - new(() => - { - PInvoke.OleInitialize(); - using var synchronizationContext = new StaSynchronizationContext(); - var previousContext = SynchronizationContext.Current; - SynchronizationContext.SetSynchronizationContext(synchronizationContext); - - try - { - var task = func(); - synchronizationContext.Run(task); - task.GetAwaiter().GetResult(); - tcs.SetResult(); - } - catch (Exception ex) - { - tcs.SetResult(); - logger?.LogWarning(ex, "An exception was occurred during the execution within STA."); - } - finally - { - SynchronizationContext.SetSynchronizationContext(previousContext); - PInvoke.OleUninitialize(); - } - }); - - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - - return tcs.Task; - } - - /// - /// Schedules the specified work to execute in a new background thread initialized with STA state. - /// - /// The type of the result returned by the function. - /// The work to execute in the STA thread. - /// A logger to capture any exception that occurs during execution. - /// A that represents the work scheduled to execute in the STA thread. - public static Task Run(Func> func, ILogger? logger) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - Thread thread = - new(() => - { - PInvoke.OleInitialize(); - using var synchronizationContext = new StaSynchronizationContext(); - var previousContext = SynchronizationContext.Current; - SynchronizationContext.SetSynchronizationContext(synchronizationContext); - - try - { - var task = func(); - synchronizationContext.Run(task); - tcs.SetResult(task.GetAwaiter().GetResult()); - } - catch (Exception ex) - { - tcs.SetResult(default); - logger?.LogWarning(ex, "An exception was occurred during the execution within STA."); - } - finally - { - SynchronizationContext.SetSynchronizationContext(previousContext); - PInvoke.OleUninitialize(); - } - }); - - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(); - - return tcs.Task; - } - - private sealed class StaSynchronizationContext : SynchronizationContext, IDisposable - { - private readonly BlockingCollection<(SendOrPostCallback Callback, object? State)> _queue = new(); - private readonly Lock _queueLock = new(); - private readonly int _threadId = Environment.CurrentManagedThreadId; - private bool _acceptingWork = true; - - public override void Post(SendOrPostCallback callback, object? state) - => TryPost(callback, state); - - public override void Send(SendOrPostCallback callback, object? state) - { - if (Environment.CurrentManagedThreadId == _threadId) - { - callback(state); - return; - } - - Exception? exception = null; - using var completed = new ManualResetEventSlim(); - if (!TryPost( - _ => - { - try - { - callback(state); - } - catch (Exception ex) - { - exception = ex; - } - finally - { - completed.Set(); - } - }, - null)) - { - throw new InvalidOperationException("The STA synchronization context has completed."); - } - completed.Wait(); - - if (exception is not null) - ExceptionDispatchInfo.Capture(exception).Throw(); - } - - public void Run(Task task) - { - var completionSignal = task.ContinueWith( - _ => Complete(), - CancellationToken.None, - TaskContinuationOptions.ExecuteSynchronously, - TaskScheduler.Default); - - foreach (var work in _queue.GetConsumingEnumerable()) - work.Callback(work.State); - - completionSignal.GetAwaiter().GetResult(); - } - - private bool TryPost(SendOrPostCallback callback, object? state) - { - lock (_queueLock) - { - if (!_acceptingWork) - return false; - - _queue.Add((callback, state)); - return true; - } - } - - private void Complete() - { - lock (_queueLock) - { - if (!_acceptingWork) - return; - - _acceptingWork = false; - _queue.CompleteAdding(); - } - } - - public void Dispose() - { - Complete(); - _queue.Dispose(); - } - } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/SystemTrayManager.cs b/src/Files.App.Storage/Windows/Managers/SystemTrayManager.cs deleted file mode 100644 index 30b6e483c0f1..000000000000 --- a/src/Files.App.Storage/Windows/Managers/SystemTrayManager.cs +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; -using WNDPROC = Windows.Win32.Extras.ManagedWNDPROC; - -namespace Files.App.Storage -{ - /// - /// Exposes a manager to create or delete an system tray icon you provide. - /// - public unsafe partial class SystemTrayManager : IDisposable - { - string _szWndClassName = null!; - string _szToolTip = null!; - HICON _hIcon = default; - private Guid _id; - private uint _dwCallbackMsgId; - Action _callback = null!; - - private HWND _hWnd = default; - private WNDPROC? _wndProc; - private uint _dwTaskbarRestartMsgId; - private bool _isShown; - - public static SystemTrayManager CreateIcon(string szWndClassName, string szToolTip, HICON hIcon, Guid id, uint dwCallbackMsgId, Action callback) - { - return new() - { - _szWndClassName = szWndClassName, - _szToolTip = szToolTip, - _hIcon = hIcon, - _id = id, - _dwCallbackMsgId = dwCallbackMsgId, - _callback = callback, - }; - } - - private bool CreateIcon() - { - if (_hWnd.IsNull) - _hWnd = CreateIconWindow(_szWndClassName); - - NOTIFYICONDATAW data = default; - data.cbSize = (uint)sizeof(NOTIFYICONDATAW); - data.hWnd = _hWnd; - data.uCallbackMessage = _dwCallbackMsgId; - data.guidItem = _id; - data.hIcon = _hIcon; - data.uFlags = NOTIFY_ICON_DATA_FLAGS.NIF_MESSAGE | NOTIFY_ICON_DATA_FLAGS.NIF_ICON | NOTIFY_ICON_DATA_FLAGS.NIF_TIP | NOTIFY_ICON_DATA_FLAGS.NIF_GUID | NOTIFY_ICON_DATA_FLAGS.NIF_SHOWTIP; - data.szTip = _szToolTip; - data.Anonymous.uVersion = 4u; - - if (_isShown) - { - return PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_DELETE, &data); - } - else - { - bool fRes = PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_DELETE, &data); - if (!fRes) return false; - - fRes = PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_ADD, &data); - if (!fRes) return false; - - fRes = PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_SETVERSION, &data); - if (!fRes) return false; - - _isShown = true; - - return true; - } - } - - public bool DeleteIcon() - { - if (_isShown) - { - NOTIFYICONDATAW data = default; - data.cbSize = (uint)sizeof(NOTIFYICONDATAW); - data.hWnd = _hWnd; - data.guidItem = _id; - data.uFlags = NOTIFY_ICON_DATA_FLAGS.NIF_GUID; - data.Anonymous.uVersion = 4u; - - return PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_DELETE, &data); - } - - return true; - } - - private HWND CreateIconWindow(string szWndClassName) - { - fixed (char* pszWndClassName = szWndClassName) - { - _wndProc ??= new(WndProc); - - WNDCLASSEXW wndClass = default; - - wndClass.cbSize = (uint)sizeof(WNDCLASSEXW); - wndClass.style = WNDCLASS_STYLES.CS_DBLCLKS; - wndClass.hInstance = PInvoke.GetModuleHandle(default(PCWSTR)); - wndClass.lpszClassName = pszWndClassName; - wndClass.lpfnWndProc = (delegate* unmanaged[Stdcall]) - Marshal.GetFunctionPointerForDelegate(_wndProc); - - PInvoke.RegisterClassEx(&wndClass); - - _dwTaskbarRestartMsgId = PInvoke.RegisterWindowMessage("TaskbarCreated"); - - return PInvoke.CreateWindowEx( - WINDOW_EX_STYLE.WS_EX_LEFT, pszWndClassName, default, - WINDOW_STYLE.WS_OVERLAPPED, 0, 0, 1, 1, HWND.Null, HMENU.Null, HINSTANCE.Null, null); - } - } - - private LRESULT WndProc(HWND hWnd, uint uMsg, WPARAM wParam, LPARAM lParam) - { - if (uMsg == _dwCallbackMsgId) - { - _callback((uint)(lParam.Value & 0xFFFF)); - - return default; - } - else if (uMsg is PInvoke.WM_DESTROY) - { - DeleteIcon(); - - return default; - } - else if (uMsg == _dwTaskbarRestartMsgId) - { - DeleteIcon(); - CreateIcon(); - } - - return PInvoke.DefWindowProc(hWnd, uMsg, wParam, lParam); - } - - public void Dispose() - { - if (!_hWnd.IsNull) - PInvoke.DestroyWindow(_hWnd); - - if (!_hIcon.IsNull) - PInvoke.DestroyIcon(_hIcon); - - _wndProc = null; - } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/TaskbarManager.cs b/src/Files.App.Storage/Windows/Managers/TaskbarManager.cs deleted file mode 100644 index f39eb887bcca..000000000000 --- a/src/Files.App.Storage/Windows/Managers/TaskbarManager.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - public unsafe class TaskbarManager : IDisposable - { - private ITaskbarList3? taskbarList; - - private static TaskbarManager? _Default = null; - public static TaskbarManager Default { get; } = _Default ??= new TaskbarManager(); - - public TaskbarManager() - { - // LINUX-TODO(taskbar): no-op on Linux; real future work is emitting com.canonical.Unity.LauncherEntry.Update over the Platform DBus session (needs an HWND-free progress abstraction) - if (!OperatingSystem.IsWindows()) - return; - - Guid CLSID_TaskbarList = typeof(TaskbarList).GUID; - HRESULT hr = PInvoke.CoCreateInstance(CLSID_TaskbarList, null, CLSCTX.CLSCTX_INPROC_SERVER, out ITaskbarList3? pTaskbarList); - - if (hr.ThrowIfFailedOnDebug().Succeeded) - hr = pTaskbarList!.HrInit().ThrowIfFailedOnDebug(); - - taskbarList = pTaskbarList; - } - - public HRESULT SetProgressValue(HWND hwnd, ulong ullCompleted, ulong ullTotal) - { - return taskbarList?.SetProgressValue(hwnd, ullCompleted, ullTotal) ?? HRESULT.E_FAIL; - } - - public HRESULT SetProgressState(HWND hwnd, TBPFLAG tbpFlags) - { - return taskbarList?.SetProgressState(hwnd, tbpFlags) ?? HRESULT.E_FAIL; - } - - public void Dispose() - { - taskbarList = null; - } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/WindowsContextMenuItem.cs b/src/Files.App.Storage/Windows/Managers/WindowsContextMenuItem.cs deleted file mode 100644 index e5798b023339..000000000000 --- a/src/Files.App.Storage/Windows/Managers/WindowsContextMenuItem.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -namespace Files.App.Storage -{ - /// - /// Represents a Windows Shell ContextMenu item. - /// - public partial class WindowsContextMenuItem - { - public WindowsContextMenuType Type { get; set; } - - public uint Id { get; set; } - - public byte[]? Icon { get; set; } - - public string? Name { get; set; } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/WindowsContextMenuType.cs b/src/Files.App.Storage/Windows/Managers/WindowsContextMenuType.cs deleted file mode 100644 index 3782c0b17e53..000000000000 --- a/src/Files.App.Storage/Windows/Managers/WindowsContextMenuType.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -namespace Files.App.Storage -{ - public enum WindowsContextMenuType - { - Normal = 0x00000000, - - Disabled = 0x00000003, - - Checked = 0x00000008, - - Highlighted = 0x00000080, - - Default = 0x00001000, - } -} diff --git a/src/Files.App.Storage/Windows/Managers/WindowsDriveManager.cs b/src/Files.App.Storage/Windows/Managers/WindowsDriveManager.cs deleted file mode 100644 index 0a5083ed164f..000000000000 --- a/src/Files.App.Storage/Windows/Managers/WindowsDriveManager.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - public unsafe sealed class WindowsDriveManager : IDisposable - { - private readonly WindowsFolderChangeWatcher _folderChangeWatcher; - private bool _isDisposed; - - public event EventHandler? DeviceAdded; - public event EventHandler? DeviceRemoved; - public event EventHandler? DeviceInserted; - public event EventHandler? DeviceEjected; - - public static WindowsDriveManager Default { get; } = new(); - - private WindowsDriveManager() - { - Guid computerFolderId = FOLDERID.FOLDERID_ComputerFolder; - _folderChangeWatcher = new( - computerFolderId, - SHCNE_ID.SHCNE_DRIVEADD | SHCNE_ID.SHCNE_DRIVEREMOVED | SHCNE_ID.SHCNE_MEDIAINSERTED | SHCNE_ID.SHCNE_MEDIAREMOVED, - recursive: true); - _folderChangeWatcher.FolderChanged += FolderChangeWatcher_FolderChanged; - } - - public void Start() - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - - _folderChangeWatcher.Start(); - } - - public void Stop() - { - _folderChangeWatcher.Stop(); - } - - private static string? NormalizeDriveId(string drivePath) - { - if (string.IsNullOrWhiteSpace(drivePath)) - return null; - - string root = SystemIO.Path.GetPathRoot(drivePath) ?? drivePath; - return root.TrimEnd(SystemIO.Path.DirectorySeparatorChar, SystemIO.Path.AltDirectorySeparatorChar); - } - - private void FolderChangeWatcher_FolderChanged(object? sender, WindowsFolderChangeEventArgs e) - { - if (string.IsNullOrEmpty(e.Path)) - return; - - string? driveId = NormalizeDriveId(e.Path); - if (string.IsNullOrEmpty(driveId)) - return; - - RaiseDriveEvent(e.ChangeType, driveId); - } - - private void RaiseDriveEvent(SHCNE_ID changeType, string driveId) - { - DeviceEventArgs args = new(driveId, driveId); - - if ((changeType & SHCNE_ID.SHCNE_DRIVEADD) != 0) - DeviceAdded?.Invoke(this, args); - - if ((changeType & SHCNE_ID.SHCNE_DRIVEREMOVED) != 0) - DeviceRemoved?.Invoke(this, args); - - if ((changeType & SHCNE_ID.SHCNE_MEDIAINSERTED) != 0) - DeviceInserted?.Invoke(this, args); - - if ((changeType & SHCNE_ID.SHCNE_MEDIAREMOVED) != 0) - DeviceEjected?.Invoke(this, args); - } - - public void Dispose() - { - if (_isDisposed) - return; - - _folderChangeWatcher.FolderChanged -= FolderChangeWatcher_FolderChanged; - _folderChangeWatcher.Dispose(); - _isDisposed = true; - } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/WindowsFolderChangeWatcher.cs b/src/Files.App.Storage/Windows/Managers/WindowsFolderChangeWatcher.cs deleted file mode 100644 index e4c348127d0e..000000000000 --- a/src/Files.App.Storage/Windows/Managers/WindowsFolderChangeWatcher.cs +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; -using Windows.Win32.UI.WindowsAndMessaging; -using WNDPROC = Windows.Win32.Extras.ManagedWNDPROC; - -namespace Files.App.Storage -{ - internal unsafe sealed class WindowsFolderChangeWatcher : IDisposable - { - private const int MaxPath = 260; - private const string WindowClassPrefix = "FilesFolderChangeNotificationWindow"; - - private readonly Guid _knownFolderId; - private readonly SHCNE_ID _changeMask; - private readonly bool _recursive; - private readonly string _windowClassName; - - private HWND _hWnd; - private WNDPROC? _wndProc; - private ITEMIDLIST* _folderPidl; - private uint _notificationMessage; - private uint _registrationId; - private int _startCount; - private bool _isDisposed; - - public event EventHandler? FolderChanged; - - public WindowsFolderChangeWatcher(Guid knownFolderId, SHCNE_ID changeMask, bool recursive) - { - _knownFolderId = knownFolderId; - _changeMask = changeMask; - _recursive = recursive; - _windowClassName = $"{WindowClassPrefix}_{Guid.NewGuid():N}"; - } - - public void Start() - { - ObjectDisposedException.ThrowIf(_isDisposed, this); - - if (Interlocked.Increment(ref _startCount) != 1) - return; - - EnsureWindow(); - RegisterShellNotifications(); - } - - public void Stop() - { - if (_startCount <= 0 || Interlocked.Decrement(ref _startCount) != 0) - return; - - UnregisterShellNotifications(); - } - - private void EnsureWindow() - { - if (!_hWnd.IsNull) - return; - - fixed (char* pszWndClassName = _windowClassName) - { - _wndProc ??= new(WndProc); - - WNDCLASSEXW wndClass = default; - wndClass.cbSize = (uint)sizeof(WNDCLASSEXW); - wndClass.hInstance = PInvoke.GetModuleHandle(default(PCWSTR)); - wndClass.lpszClassName = pszWndClassName; - wndClass.lpfnWndProc = (delegate* unmanaged[Stdcall]) - Marshal.GetFunctionPointerForDelegate(_wndProc); - - PInvoke.RegisterClassEx(&wndClass); - - _notificationMessage = PInvoke.RegisterWindowMessage(_windowClassName); - _hWnd = PInvoke.CreateWindowEx( - WINDOW_EX_STYLE.WS_EX_LEFT, - pszWndClassName, - default, - WINDOW_STYLE.WS_OVERLAPPED, - 0, - 0, - 1, - 1, - HWND.Null, - HMENU.Null, - HINSTANCE.Null, - null); - } - } - - private void RegisterShellNotifications() - { - if (_registrationId != 0) - return; - - HRESULT hr = PInvoke.SHGetKnownFolderIDList( - in _knownFolderId, - 0, - null, - out ITEMIDLIST* pidl); - if (hr.Failed || pidl is null) - return; - - _folderPidl = pidl; - - SHChangeNotifyEntry entry = new() - { - pidl = _folderPidl, - fRecursive = _recursive, - }; - - _registrationId = PInvoke.SHChangeNotifyRegister( - _hWnd, - SHCNRF_SOURCE.SHCNRF_ShellLevel | SHCNRF_SOURCE.SHCNRF_InterruptLevel | SHCNRF_SOURCE.SHCNRF_NewDelivery, - (int)_changeMask, - _notificationMessage, - 1, - in entry); - } - - private void UnregisterShellNotifications() - { - if (_registrationId != 0) - { - PInvoke.SHChangeNotifyDeregister(_registrationId); - _registrationId = 0; - } - - if (_folderPidl is not null) - { - PInvoke.CoTaskMemFree(_folderPidl); - _folderPidl = null; - } - } - - private LRESULT WndProc(HWND hWnd, uint uMsg, WPARAM wParam, LPARAM lParam) - { - if (uMsg == _notificationMessage) - { - ProcessShellNotification(wParam, lParam); - return default; - } - - return PInvoke.DefWindowProc(hWnd, uMsg, wParam, lParam); - } - - private void ProcessShellNotification(WPARAM wParam, LPARAM lParam) - { - ITEMIDLIST** ppidls = null; - int eventId = 0; - HANDLE lockHandle = PInvoke.SHChangeNotification_Lock( - new HANDLE((nint)wParam.Value), - unchecked((uint)lParam.Value), - &ppidls, - &eventId); - if (lockHandle.IsNull) - return; - - try - { - string? path = ppidls is null ? null : GetPathFromPidl(ppidls[0]); - string? otherPath = ppidls is null ? null : GetPathFromPidl(ppidls[1]); - FolderChanged?.Invoke(this, new WindowsFolderChangeEventArgs((SHCNE_ID)eventId, path, otherPath)); - } - finally - { - PInvoke.SHChangeNotification_Unlock(lockHandle); - } - } - - private static string? GetPathFromPidl(ITEMIDLIST* pidl) - { - if (pidl is null) - return null; - - Span path = stackalloc char[MaxPath]; - fixed (char* pathBuffer = path) - { - if (!PInvoke.SHGetPathFromIDList(pidl, pathBuffer)) - return null; - } - - int length = path.IndexOf('\0'); - return path[..(length < 0 ? path.Length : length)].ToString(); - } - - public void Dispose() - { - if (_isDisposed) - return; - - UnregisterShellNotifications(); - - if (!_hWnd.IsNull) - { - PInvoke.DestroyWindow(_hWnd); - _hWnd = HWND.Null; - } - - fixed (char* pszWndClassName = _windowClassName) - PInvoke.UnregisterClass(pszWndClassName, PInvoke.GetModuleHandle(default(PCWSTR))); - - _wndProc = null; - _isDisposed = true; - } - } - - internal sealed class WindowsFolderChangeEventArgs : EventArgs - { - public SHCNE_ID ChangeType { get; } - - public string? Path { get; } - - public string? OtherPath { get; } - - public WindowsFolderChangeEventArgs(SHCNE_ID changeType, string? path, string? otherPath) - { - ChangeType = changeType; - Path = path; - OtherPath = otherPath; - } - } -} diff --git a/src/Files.App.Storage/Windows/Managers/WindowsObjectPicker.cs b/src/Files.App.Storage/Windows/Managers/WindowsObjectPicker.cs deleted file mode 100644 index baf480000ba1..000000000000 --- a/src/Files.App.Storage/Windows/Managers/WindowsObjectPicker.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Microsoft.Extensions.Logging; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using System.Security.Principal; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.Networking.ActiveDirectory; -using Windows.Win32.System.Variant; - -namespace Files.App.Storage -{ - public static unsafe class WindowsObjectPicker - { - private const string ObjectSidAttributeName = "objectSid"; - - public static Task OpenObjectPickerAsync(nint ownerHWnd, ILogger? logger) - => STATask.Run(() => OpenObjectPicker((HWND)ownerHWnd), logger); - - private static string? OpenObjectPicker(HWND ownerHWnd) - { - Guid CLSID_DsObjectPicker = PInvoke.CLSID_DsObjectPicker; - - HRESULT hr = PInvoke.CoCreateInstance(CLSID_DsObjectPicker, null, CLSCTX.CLSCTX_INPROC_SERVER, out IDsObjectPicker? pObjectPicker); - if (hr.ThrowIfFailedOnDebug().Failed || pObjectPicker is null) - return null; - - DSOP_SCOPE_INIT_INFO* scopeInitInfos = stackalloc DSOP_SCOPE_INIT_INFO[2]; - scopeInitInfos[0] = CreateScopeInitInfo(PInvoke.DSOP_SCOPE_TYPE_TARGET_COMPUTER, true); - scopeInitInfos[1] = CreateScopeInitInfo( - PInvoke.DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN | - PInvoke.DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN | - PInvoke.DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN | - PInvoke.DSOP_SCOPE_TYPE_GLOBAL_CATALOG | - PInvoke.DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN | - PInvoke.DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN | - PInvoke.DSOP_SCOPE_TYPE_WORKGROUP | - PInvoke.DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE | - PInvoke.DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE, - false); - - fixed (char* pszObjectSidAttributeName = ObjectSidAttributeName) - { - PCWSTR* attributeNames = stackalloc PCWSTR[1]; - attributeNames[0] = pszObjectSidAttributeName; - - DSOP_INIT_INFO initInfo = default; - initInfo.cbSize = (uint)sizeof(DSOP_INIT_INFO); - initInfo.cDsScopeInfos = 2; - initInfo.aDsScopeInfos = scopeInitInfos; - initInfo.cAttributesToFetch = 1; - initInfo.apwzAttributeNames = attributeNames; - - hr = pObjectPicker.Initialize(ref initInfo); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - } - - hr = pObjectPicker.InvokeDialog(ownerHWnd, out IDataObject pSelections); - if (hr == HRESULT.S_FALSE || hr.ThrowIfFailedOnDebug().Failed) - return null; - - return GetSelectedSid(pSelections); - } - - private static DSOP_SCOPE_INIT_INFO CreateScopeInitInfo(uint scopeType, bool startingScope) - { - const uint defaultFilter = - PInvoke.DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS | - PInvoke.DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS; - - const uint upLevelFilter = - PInvoke.DSOP_FILTER_INCLUDE_ADVANCED_VIEW | - PInvoke.DSOP_FILTER_USERS | - PInvoke.DSOP_FILTER_BUILTIN_GROUPS | - PInvoke.DSOP_FILTER_WELL_KNOWN_PRINCIPALS | - PInvoke.DSOP_FILTER_UNIVERSAL_GROUPS_DL | - PInvoke.DSOP_FILTER_UNIVERSAL_GROUPS_SE | - PInvoke.DSOP_FILTER_GLOBAL_GROUPS_DL | - PInvoke.DSOP_FILTER_GLOBAL_GROUPS_SE | - PInvoke.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL | - PInvoke.DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE | - PInvoke.DSOP_FILTER_CONTACTS | - PInvoke.DSOP_FILTER_COMPUTERS | - PInvoke.DSOP_FILTER_SERVICE_ACCOUNTS; - - const uint downLevelFilter = - PInvoke.DSOP_DOWNLEVEL_FILTER_USERS | - PInvoke.DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS | - PInvoke.DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS | - PInvoke.DSOP_DOWNLEVEL_FILTER_COMPUTERS | - PInvoke.DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS; - - DSOP_SCOPE_INIT_INFO info = default; - info.cbSize = (uint)sizeof(DSOP_SCOPE_INIT_INFO); - info.flType = scopeType; - info.flScope = startingScope - ? PInvoke.DSOP_SCOPE_FLAG_STARTING_SCOPE | defaultFilter - : defaultFilter; - info.FilterFlags.Uplevel.flBothModes = upLevelFilter; - info.FilterFlags.flDownlevel = downLevelFilter; - - return info; - } - - private static string? GetSelectedSid(IDataObject pSelections) - { - uint clipboardFormat = PInvoke.RegisterClipboardFormat(PInvoke.CFSTR_DSOP_DS_SELECTION_LIST); - - if (clipboardFormat is 0 || clipboardFormat > ushort.MaxValue) - return null; - - FORMATETC format = default; - format.cfFormat = (ushort)clipboardFormat; - format.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT; - format.lindex = -1; - format.tymed = (uint)TYMED.TYMED_HGLOBAL; - - STGMEDIUM medium = default; - medium.tymed = TYMED.TYMED_HGLOBAL; - - HRESULT hr = pSelections.GetData(format, out medium); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - void* pvSelectionList = PInvoke.GlobalLock(medium.u.hGlobal); - if (pvSelectionList is null) - { - PInvoke.ReleaseStgMedium(ref medium); - return null; - } - - try - { - DS_SELECTION_LIST* pSelectionList = (DS_SELECTION_LIST*)pvSelectionList; - if (pSelectionList->cItems is 0 || pSelectionList->cFetchedAttributes is 0) - return null; - - var selectionsAsSpan = pSelectionList->aDsSelection.AsSpan((int)pSelectionList->cItems); - fixed (DS_SELECTION_unmanaged* pSelection = selectionsAsSpan) - { - if (pSelection->pvarFetchedAttributes is null) - return null; - - return GetSidString(pSelection->pvarFetchedAttributes); - } - } - finally - { - PInvoke.GlobalUnlock(medium.u.hGlobal); - PInvoke.ReleaseStgMedium(ref medium); - } - } - - private static string? GetSidString(ComVariant* objectSidVariant) - { - VarEnum variantType = objectSidVariant->VarType; - if ((variantType & VarEnum.VT_ARRAY) is 0 || (variantType & (VarEnum)0x0FFF) is not VarEnum.VT_UI1) - return null; - - ref nint rawValue = ref objectSidVariant->GetRawDataRef(); - SAFEARRAY* pSafeArray = (variantType & VarEnum.VT_BYREF) is not 0 - ? *(SAFEARRAY**)rawValue - : (SAFEARRAY*)rawValue; - - if (pSafeArray is null || PInvoke.SafeArrayGetDim(pSafeArray) is not 1) - return null; - - int lowerBound = 0, upperBound = 0; - if (PInvoke.SafeArrayGetLBound(pSafeArray, 1, out lowerBound).ThrowIfFailedOnDebug().Failed || - PInvoke.SafeArrayGetUBound(pSafeArray, 1, out upperBound).ThrowIfFailedOnDebug().Failed || - upperBound < lowerBound) - return null; - - if (PInvoke.SafeArrayAccessData(pSafeArray, out void* pSidBytes).ThrowIfFailedOnDebug().Failed || pSidBytes is null) - return null; - - try - { - int length = upperBound - lowerBound + 1; - byte[] sidBytes = new ReadOnlySpan((byte*)pSidBytes, length).ToArray(); - - return new SecurityIdentifier(sidBytes, 0).Value; - } - finally - { - PInvoke.SafeArrayUnaccessData(pSafeArray); - } - } - } -} diff --git a/src/Files.App.Storage/Windows/WindowsBulkOperations.cs b/src/Files.App.Storage/Windows/WindowsBulkOperations.cs deleted file mode 100644 index b3bff9141461..000000000000 --- a/src/Files.App.Storage/Windows/WindowsBulkOperations.cs +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - /// - /// Handles bulk file operations in Windows, such as copy, move, delete, create, and rename, supporting progress tracking and event notifications. - /// - public unsafe partial class WindowsBulkOperations : IDisposable - { - // Fields - - private readonly IFileOperation _fileOperation; - private readonly IFileOperationProgressSink _progressSink; - private readonly uint _progressSinkCookie; - - // Events - - /// An event that is triggered when bulk operations are completed. - public event EventHandler? OperationsFinished; - - /// An event that is triggered when an item is copied during bulk operations. - public event EventHandler? ItemCopied; - - /// An event that is triggered when an item is deleted during bulk operations. - public event EventHandler? ItemDeleted; - - /// An event that is triggered when an item is moved during bulk operations. - public event EventHandler? ItemMoved; - - /// An event that is triggered when a new item is created. - public event EventHandler? ItemCreated; - - /// An event that is triggered when an item is renamed. - public event EventHandler? ItemRenamed; - - /// An event that occurs when an item is being copied during bulk operations. - public event EventHandler? ItemCopying; - - /// An event that is triggered when an item is being deleted. - public event EventHandler? ItemDeleting; - - /// An event that is triggered when an item is being moved in bulk operations. - public event EventHandler? ItemMoving; - - /// An event that is triggered when an item is being created in bulk operations. - public event EventHandler? ItemCreating; - - /// An event that is triggered when an item is being renamed. - public event EventHandler? ItemRenaming; - - /// An event that is triggered when operations start. - public event EventHandler? OperationsStarted; - - /// An event that is triggered to indicate progress updates. - public event ProgressChangedEventHandler? ProgressUpdated; - - // Constructor - - /// - /// Initializes a instance for file operations on Windows. - /// - /// Specifies the window handle that will own the file operation dialogs. - /// Defines the behavior of the file operation, such as allowing undo and suppressing directory confirmation. - public WindowsBulkOperations(HWND ownerHWnd = default, FILEOPERATION_FLAGS flags = FILEOPERATION_FLAGS.FOF_ALLOWUNDO | FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR) - { - HRESULT hr = PInvoke.CoCreateInstance(typeof(FileOperation).GUID, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IFileOperation? fileOperation); - hr.ThrowIfFailedOnDebug(); - - _fileOperation = fileOperation!; - - if (ownerHWnd != default) - hr = _fileOperation.SetOwnerWindow(ownerHWnd).ThrowIfFailedOnDebug(); - - hr = _fileOperation.SetOperationFlags(flags).ThrowIfFailedOnDebug(); - - _progressSink = new WindowsBulkOperationsSink(this); - hr = _fileOperation.Advise(_progressSink, out var progressSinkCookie).ThrowIfFailedOnDebug(); - _progressSinkCookie = progressSinkCookie; - } - - /// - /// Queues a copy operation. - /// - /// - /// - /// - /// If this method succeeds, it returns . Otherwise, it returns an error code. - public unsafe HRESULT QueueCopyOperation(WindowsStorable targetItem, WindowsFolder destinationFolder, string? copyName) - { - fixed (char* pszCopyName = copyName) - return _fileOperation.CopyItem(targetItem.ThisPtr, destinationFolder.ThisPtr, pszCopyName, _progressSink); - } - - /// - /// Queues a delete operation. - /// - /// - /// If this method succeeds, it returns . Otherwise, it returns an error code. - public unsafe HRESULT QueueDeleteOperation(WindowsStorable targetItem) - { - return _fileOperation.DeleteItem(targetItem.ThisPtr, _progressSink); - } - - /// - /// Queues a move operation. - /// - /// - /// - /// - /// If this method succeeds, it returns . Otherwise, it returns an error code. - public unsafe HRESULT QueueMoveOperation(WindowsStorable targetItem, WindowsFolder destinationFolder, string? newName) - { - fixed (char* pszNewName = newName) - return _fileOperation.MoveItem(targetItem.ThisPtr, destinationFolder.ThisPtr, pszNewName, null!); - } - - /// - /// Queues a create operation. - /// - /// - /// - /// - /// - /// If this method succeeds, it returns . Otherwise, it returns an error code. - public unsafe HRESULT QueueCreateOperation(WindowsFolder destinationFolder, FILE_FLAGS_AND_ATTRIBUTES fileAttributes, string name, string? templateName) - { - fixed (char* pszName = name, pszTemplateName = templateName) - return _fileOperation.NewItem(destinationFolder.ThisPtr, (uint)fileAttributes, pszName, pszTemplateName, _progressSink); - } - - /// - /// Queues a rename operation. - /// - /// - /// - /// If this method succeeds, it returns . Otherwise, it returns an error code. - public unsafe HRESULT QueueRenameOperation(WindowsStorable targetItem, string newName) - { - fixed (char* pszNewName = newName) - return _fileOperation.RenameItem(targetItem.ThisPtr, pszNewName, _progressSink); - } - - /// - /// Performs the all queued operations. - /// - /// If this method succeeds, it returns . Otherwise, it returns an error code. - public unsafe HRESULT PerformAllOperations() - { - return _fileOperation.PerformOperations(); - } - - // Disposer - - /// - public unsafe void Dispose() - { - _fileOperation.Unadvise(_progressSinkCookie); - } - } -} diff --git a/src/Files.App.Storage/Windows/WindowsBulkOperationsEventArgs.cs b/src/Files.App.Storage/Windows/WindowsBulkOperationsEventArgs.cs deleted file mode 100644 index a9127ad626aa..000000000000 --- a/src/Files.App.Storage/Windows/WindowsBulkOperationsEventArgs.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - [DebuggerDisplay("{" + nameof(ToString) + "()}")] - public class WindowsBulkOperationsEventArgs(_TRANSFER_SOURCE_FLAGS flags = _TRANSFER_SOURCE_FLAGS.TSF_NORMAL, WindowsStorable? sourceItem = null, WindowsFolder? destinationFolder = null, WindowsStorable? newlyCreated = null, string? name = null, string? templateName = null, HRESULT result = default) - : EventArgs - { - public _TRANSFER_SOURCE_FLAGS Flags { get; set; } = flags; - - public WindowsStorable? SourceItem { get; set; } = sourceItem; - - public WindowsFolder? DestinationFolder { get; set; } = destinationFolder; - - public WindowsStorable? NewlyCreated { get; set; } = newlyCreated; - - public string? Name { get; set; } = name; - - public string? TemplateName { get; set; } = templateName; - - public HRESULT Result { get; protected set; } = result; - - public override string ToString() - => $"Hr:\"{Result}\"; Src:\"{SourceItem}\"; Dst:\"{DestinationFolder}\"; New:\"{NewlyCreated}\"; Name:\"{Name}\""; - } -} diff --git a/src/Files.App.Storage/Windows/WindowsBulkOperationsSink.Methods.cs b/src/Files.App.Storage/Windows/WindowsBulkOperationsSink.Methods.cs deleted file mode 100644 index da105ecaf068..000000000000 --- a/src/Files.App.Storage/Windows/WindowsBulkOperationsSink.Methods.cs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; -using System.Runtime.InteropServices.Marshalling; - -namespace Files.App.Storage -{ - public sealed partial class WindowsBulkOperations : IDisposable - { - [GeneratedComClass] - private sealed partial class WindowsBulkOperationsSink : IFileOperationProgressSink - { - private readonly WeakReference _operationsReference; - - public WindowsBulkOperationsSink(WindowsBulkOperations operations) - { - _operationsReference = new(operations); - } - - public HRESULT StartOperations() - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.OperationsStarted?.Invoke(operations, EventArgs.Empty); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT FinishOperations(HRESULT hrResult) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.OperationsFinished?.Invoke(operations, new(result: hrResult)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PreRenameItem(uint dwFlags, IShellItem pSource, PCWSTR pszNewName) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemRenaming?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), null, null, pszNewName.ToString(), null, default)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PostRenameItem(uint dwFlags, IShellItem pSource, PCWSTR pszNewName, HRESULT hrRename, IShellItem psiNewlyCreated) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemRenamed?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), null, WindowsStorable.TryParse(psiNewlyCreated), pszNewName.ToString(), null, hrRename)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PreMoveItem(uint dwFlags, IShellItem pSource, IShellItem psiDestinationFolder, PCWSTR pszNewName) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemMoving?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), new WindowsFolder(psiDestinationFolder), null, pszNewName.ToString(), null, default)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PostMoveItem(uint dwFlags, IShellItem pSource, IShellItem psiDestinationFolder, PCWSTR pszNewName, HRESULT hrMove, IShellItem psiNewlyCreated) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemMoved?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), new WindowsFolder(psiDestinationFolder), WindowsStorable.TryParse(psiNewlyCreated), pszNewName.ToString(), null, hrMove)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PreCopyItem(uint dwFlags, IShellItem pSource, IShellItem psiDestinationFolder, PCWSTR pszNewName) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemCopying?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), new WindowsFolder(psiDestinationFolder), null, pszNewName.ToString(), null, default)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PostCopyItem(uint dwFlags, IShellItem pSource, IShellItem psiDestinationFolder, PCWSTR pszNewName, HRESULT hrCopy, IShellItem psiNewlyCreated) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemCopied?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), new WindowsFolder(psiDestinationFolder), WindowsStorable.TryParse(psiNewlyCreated), pszNewName.ToString(), null, hrCopy)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PreDeleteItem(uint dwFlags, IShellItem pSource) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemDeleting?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), null, null, null, null, default)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PostDeleteItem(uint dwFlags, IShellItem pSource, HRESULT hrDelete, IShellItem psiNewlyCreated) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemDeleted?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, WindowsStorable.TryParse(pSource), null, WindowsStorable.TryParse(psiNewlyCreated), null, null, hrDelete)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PreNewItem(uint dwFlags, IShellItem psiDestinationFolder, PCWSTR pszNewName) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemCreating?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, null, new WindowsFolder(psiDestinationFolder), null, pszNewName.ToString(), null, default)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT PostNewItem(uint dwFlags, IShellItem psiDestinationFolder, PCWSTR pszNewName, PCWSTR pszTemplateName, uint dwFileAttributes, HRESULT hrNew, IShellItem psiNewItem) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - operations.ItemCreated?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)dwFlags, null, new WindowsFolder(psiDestinationFolder), WindowsStorable.TryParse(psiNewItem), pszNewName.ToString(), pszTemplateName.ToString(), hrNew)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT UpdateProgress(uint iWorkTotal, uint iWorkSoFar) - { - if (_operationsReference.TryGetTarget(out var operations)) - { - var percentage = iWorkTotal is 0 ? 0 : iWorkSoFar * 100.0 / iWorkTotal; - operations.ProgressUpdated?.Invoke(operations, new((int)percentage, null)); - return HRESULT.S_OK; - } - - return HRESULT.E_FAIL; - } - - public HRESULT ResetTimer() - { - return HRESULT.E_NOTIMPL; - } - - public HRESULT PauseTimer() - { - return HRESULT.E_NOTIMPL; - } - - public HRESULT ResumeTimer() - { - return HRESULT.E_NOTIMPL; - } - } - } -} diff --git a/src/Files.App.Storage/Windows/WindowsFile.cs b/src/Files.App.Storage/Windows/WindowsFile.cs deleted file mode 100644 index f78618db4728..000000000000 --- a/src/Files.App.Storage/Windows/WindowsFile.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.IO; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - [DebuggerDisplay("{" + nameof(ToString) + "()}")] - public class WindowsFile : WindowsStorable, IWindowsFile - { - public WindowsFile(IShellItem ptr) - { - ThisPtr = ptr; - } - - public Task OpenStreamAsync(FileAccess accessMode, CancellationToken cancellationToken = default) - { - throw new NotImplementedException(); - } - } -} diff --git a/src/Files.App.Storage/Windows/WindowsFolder.cs b/src/Files.App.Storage/Windows/WindowsFolder.cs deleted file mode 100644 index d587473715f3..000000000000 --- a/src/Files.App.Storage/Windows/WindowsFolder.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.CompilerServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.SystemServices; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - [DebuggerDisplay("{" + nameof(ToString) + "()}")] - public unsafe class WindowsFolder : WindowsStorable, IWindowsFolder - { - /// - public IContextMenu? ShellNewMenu - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - set; - } - - public WindowsFolder(IShellItem ptr) - { - ThisPtr = ptr; - } - - public WindowsFolder(Guid folderId) - { - HRESULT hr = PInvoke.SHGetKnownFolderItem(folderId, KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, null, out IShellItem shellItem); - if (hr.Failed) - { - hr = PInvoke.SHCreateItemFromParsingName($"Shell:::{folderId:B}", null, out shellItem); - - // Invalid FOLDERID; this should never happen. - hr.ThrowOnFailure(); - } - - ThisPtr = shellItem; - } - - public IAsyncEnumerable GetItemsAsync(StorableType type = StorableType.All, CancellationToken cancellationToken = default) - { - HRESULT hr = ThisPtr.BindToHandler(null, PInvoke.BHID_EnumItems, out IEnumShellItems? pEnumShellItems); - if (hr.ThrowIfFailedOnDebug().Failed) - return Enumerable.Empty().ToAsyncEnumerable(); - - List childItems = []; - IShellItem[] pChildShellItems = new IShellItem[1]; - - while ((hr = pEnumShellItems!.Next(1, pChildShellItems, null)) == HRESULT.S_OK) - { - IShellItem pChildShellItem = pChildShellItems[0]; - bool isFolder = pChildShellItem.GetAttributes(SFGAO_FLAGS.SFGAO_FOLDER, out var dwAttributes).Succeeded && dwAttributes is SFGAO_FLAGS.SFGAO_FOLDER; - - if (type.HasFlag(StorableType.File) && !isFolder) - { - childItems.Add(new WindowsFile(pChildShellItem)); - } - else if (type.HasFlag(StorableType.Folder) && isFolder) - { - childItems.Add(new WindowsFolder(pChildShellItem)); - } - } - - if (hr.ThrowIfFailedOnDebug().Failed) - return Enumerable.Empty().ToAsyncEnumerable(); - - return childItems.ToAsyncEnumerable(); - } - - public override void Dispose() - { - base.Dispose(); - ShellNewMenu = null; - } - } -} diff --git a/src/Files.App.Storage/Windows/WindowsStorable.cs b/src/Files.App.Storage/Windows/WindowsStorable.cs deleted file mode 100644 index f2df4d2dc78f..000000000000 --- a/src/Files.App.Storage/Windows/WindowsStorable.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.CompilerServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.SystemServices; -using Windows.Win32.UI.Shell; - -namespace Files.App.Storage -{ - public abstract class WindowsStorable : IWindowsStorable - { - /// - public IShellItem ThisPtr - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - set; - } = null!; - - /// - public IContextMenu? ContextMenu - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - set; - } - - /// - public string Id => this.GetDisplayName(SIGDN.SIGDN_FILESYSPATH); - - /// - public string Name => this.GetDisplayName(SIGDN.SIGDN_PARENTRELATIVEFORUI); - - public static WindowsStorable? TryParse(string szPath) - { - HRESULT hr = PInvoke.SHCreateItemFromParsingName(szPath, null, out IShellItem pShellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - return TryParse(pShellItem); - } - - public static WindowsStorable? TryParse(IShellItem? pShellItem) - { - if (pShellItem is null) - return null; - - bool isFolder = pShellItem.GetAttributes(SFGAO_FLAGS.SFGAO_FOLDER, out var returnedAttributes).Succeeded && returnedAttributes is SFGAO_FLAGS.SFGAO_FOLDER; - - return isFolder ? new WindowsFolder(pShellItem) : new WindowsFile(pShellItem); - } - - /// - public Task GetParentAsync(CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - - HRESULT hr = ThisPtr.GetParent(out var pParentFolder); - if (hr.ThrowIfFailedOnDebug().Failed) - return Task.FromResult(null); - - return Task.FromResult(new WindowsFolder(pParentFolder)); - } - - /// - public override bool Equals(object? obj) - { - return Equals(obj as IWindowsStorable); - } - - /// - public override int GetHashCode() - { - return HashCode.Combine(Id, Name); - } - - /// - public virtual void Dispose() - { - ContextMenu = null; - } - - /// - public override string ToString() - { - return this.GetDisplayName(); - } - - /// - public bool Equals(IWindowsStorable? other) - { - if (other is null) - return false; - - return ThisPtr.Compare(other.ThisPtr, (uint)_SICHINTF.SICHINT_DISPLAY, out int order).Succeeded && order is 0; - } - - public static bool operator ==(WindowsStorable left, WindowsStorable right) - => left.Equals(right); - - public static bool operator !=(WindowsStorable left, WindowsStorable right) - => !(left == right); - } -} diff --git a/src/Files.App.UnoVirtualization/Files.App.UnoVirtualization.csproj b/src/Files.App.UnoVirtualization/Files.App.UnoVirtualization.csproj index 6927625a449d..5363ca9fb23f 100644 --- a/src/Files.App.UnoVirtualization/Files.App.UnoVirtualization.csproj +++ b/src/Files.App.UnoVirtualization/Files.App.UnoVirtualization.csproj @@ -10,7 +10,6 @@ x86;x64;arm64 true false - true diff --git a/src/Files.App/Actions/Content/Archives/Compress/BaseCompressArchiveAction.cs b/src/Files.App/Actions/Content/Archives/Compress/BaseCompressArchiveAction.cs index 74e6863c9d2f..11297ce10473 100644 --- a/src/Files.App/Actions/Content/Archives/Compress/BaseCompressArchiveAction.cs +++ b/src/Files.App/Actions/Content/Archives/Compress/BaseCompressArchiveAction.cs @@ -68,9 +68,7 @@ private bool IsContextPageTypeAdaptedToCommand() return context.PageType != ContentPageTypes.RecycleBin && (context.PageType != ContentPageTypes.ZipFolder -#if !WINDOWS || Ioc.Default.GetRequiredService().CanWriteEntries -#endif ) && context.PageType != ContentPageTypes.ReleaseNotes && context.PageType != ContentPageTypes.Settings && diff --git a/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.Windows.cs b/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.Windows.cs deleted file mode 100644 index 53f80ccb7299..000000000000 --- a/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.Windows.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Dialogs; -using Microsoft.UI.Xaml.Controls; -using System.Text; -using Windows.Foundation.Metadata; -using Windows.Storage; - -namespace Files.App.Actions -{ - internal abstract class BaseDecompressArchiveAction : BaseUIAction, IAction - { - protected readonly IContentPageContext context; - protected IStorageArchiveService StorageArchiveService { get; } = Ioc.Default.GetRequiredService(); - - public abstract string Label { get; } - - public abstract string Description { get; } - - public virtual ActionCategory Category - => ActionCategory.Archive; - - public virtual HotKey HotKey - => HotKey.None; - - public override bool IsExecutable => - (IsContextPageTypeAdaptedToCommand() && - CanDecompressSelectedItems() || - CanDecompressInsideArchive()) && - UIHelpers.CanShowDialog; - - public BaseDecompressArchiveAction() - { - context = Ioc.Default.GetRequiredService(); - - context.PropertyChanged += Context_PropertyChanged; - } - - public abstract Task ExecuteAsync(object? parameter = null); - - protected bool IsContextPageTypeAdaptedToCommand() - { - return - context.PageType != ContentPageTypes.RecycleBin && - context.PageType != ContentPageTypes.ZipFolder && - context.PageType != ContentPageTypes.ReleaseNotes && - context.PageType != ContentPageTypes.Settings && - context.PageType != ContentPageTypes.None; - } - - protected async Task DecompressArchiveHereAsync(bool smart = false) - { - if (context.SelectedItems.Count is 0) - return; - - var selectedItems = context.SelectedItems.ToList(); - var currentFolderPath = context.ShellPage?.ShellViewModel?.CurrentFolder?.ItemPath ?? string.Empty; - BaseStorageFolder? currentFolder = await StorageHelpers.ToStorageItem(currentFolderPath); - - foreach (var selectedItem in selectedItems) - { - var password = string.Empty; - BaseStorageFile? archive = await StorageHelpers.ToStorageItem(selectedItem.ItemPath!); - - if (archive?.Path is null) - return; - - if (await FilesystemTasks.Wrap(() => StorageArchiveService.IsEncryptedAsync(archive.Path))) - { - DecompressArchiveDialogViewModel decompressArchiveViewModel = new(archive) - { - IsArchiveEncrypted = true, - ShowPathSelection = false - }; - - DecompressArchiveDialog decompressArchiveDialog = new() { ViewModel = decompressArchiveViewModel }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - decompressArchiveDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - ContentDialogResult option = await decompressArchiveDialog.TryShowAsync(); - if (option != ContentDialogResult.Primary) - return; - - if (decompressArchiveViewModel.Password is not null) - password = Encoding.UTF8.GetString(decompressArchiveViewModel.Password); - } - - BaseStorageFolder? destinationFolder = null; - - var isMultipleItems = await StorageArchiveService.HasMultipleTopLevelEntriesAsync(archive.Path, password); - - if (smart && currentFolder is not null && isMultipleItems) - { - destinationFolder = - await FilesystemTasks.WrapNullable(() => - currentFolder.CreateFolderAsync( - SystemIO.Path.GetFileNameWithoutExtension(archive.Path), - CreationCollisionOption.GenerateUniqueName).AsTask()); - } - else - { - destinationFolder = currentFolder; - } - - // Operate decompress - var result = await FilesystemTasks.Wrap(() => - StorageArchiveService.DecompressAsync(selectedItem.ItemPath!, destinationFolder?.Path ?? string.Empty, password)); - } - } - - protected virtual bool CanDecompressInsideArchive() - { - return false; - } - - protected virtual bool CanDecompressSelectedItems() - { - return StorageArchiveService.CanDecompress(context.SelectedItems); - } - - protected virtual void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) - { - switch (e.PropertyName) - { - case nameof(IContentPageContext.SelectedItems): - case nameof(IContentPageContext.Folder): - OnPropertyChanged(nameof(IsExecutable)); - break; - } - } - } -} diff --git a/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.cs b/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.cs index 9e8af621965c..69aab7206471 100644 --- a/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.cs +++ b/src/Files.App/Actions/Content/Archives/Decompress/BaseDecompressArchiveAction.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.App.Dialogs; using Microsoft.UI.Xaml.Controls; using System.Text; @@ -120,4 +119,3 @@ protected virtual void Context_PropertyChanged(object? sender, PropertyChangedEv } } -#endif diff --git a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.Windows.cs b/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.Windows.cs deleted file mode 100644 index 5a1d4a8f4e68..000000000000 --- a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.Windows.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Dialogs; -using Files.Shared.Helpers; -using Microsoft.UI.Xaml.Controls; -using System.IO; -using System.Text; -using Windows.Foundation.Metadata; -using Windows.Storage; - -namespace Files.App.Actions -{ - [GeneratedRichCommand] - internal sealed partial class DecompressArchiveAction : BaseDecompressArchiveAction - { - private readonly IUserSettingsService UserSettingsService = Ioc.Default.GetRequiredService(); - - public override string Label - => Strings.ExtractFiles.GetLocalizedResource(); - - public override string Description - => Strings.DecompressArchiveDescription.GetLocalizedFormatResource(context.SelectedItems.Count); - - public string AccessKey - => "E"; - - public override HotKey HotKey - => new(Keys.E, KeyModifiers.Ctrl); - - public DecompressArchiveAction() - { - } - - public override async Task ExecuteAsync(object? parameter = null) - { - if (context.ShellPage is null) - return; - - var archivePath = GetArchivePath(); - - if (string.IsNullOrEmpty(archivePath)) - return; - - BaseStorageFile? archive = await StorageHelpers.ToStorageItem(archivePath); - - if (archive?.Path is null) - return; - - var isArchiveEncrypted = await FilesystemTasks.Wrap(() => StorageArchiveService.IsEncryptedAsync(archive.Path)); - var isArchiveEncodingUndetermined = await FilesystemTasks.Wrap(() => StorageArchiveService.IsEncodingUndeterminedAsync(archive.Path)); - Encoding? detectedEncoding = null; - if (isArchiveEncodingUndetermined) - { - detectedEncoding = await FilesystemTasks.Wrap(() => StorageArchiveService.DetectEncodingAsync(archive.Path)); - } - var password = string.Empty; - Encoding? encoding = null; - - DecompressArchiveDialogViewModel decompressArchiveViewModel = new(archive) - { - IsArchiveEncrypted = isArchiveEncrypted, - IsArchiveEncodingUndetermined = isArchiveEncodingUndetermined, - ShowPathSelection = true, - DetectedEncoding = detectedEncoding, - }; - DecompressArchiveDialog decompressArchiveDialog = new() { ViewModel = decompressArchiveViewModel }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - decompressArchiveDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - ContentDialogResult option = await decompressArchiveDialog.TryShowAsync(); - if (option != ContentDialogResult.Primary) - return; - - if (isArchiveEncrypted && decompressArchiveViewModel.Password is not null) - password = Encoding.UTF8.GetString(decompressArchiveViewModel.Password); - - encoding = decompressArchiveViewModel.SelectedEncoding.Encoding; - - // Check if archive still exists - if (!StorageHelpers.Exists(archive.Path)) - return; - - BaseStorageFolder? destinationFolder = decompressArchiveViewModel.DestinationFolder; - string destinationFolderPath = decompressArchiveViewModel.DestinationFolderPath; - - // Save extraction location for future use - SaveExtractionLocation(destinationFolderPath); - - if (destinationFolder is null) - { - BaseStorageFolder? parentFolder = await StorageHelpers.ToStorageItem(Path.GetDirectoryName(archive.Path) ?? string.Empty); - if (parentFolder is null) - return; - - destinationFolder = await FilesystemTasks.WrapNullable(() => parentFolder.CreateFolderAsync(Path.GetFileName(destinationFolderPath), CreationCollisionOption.GenerateUniqueName).AsTask()); - } - - // Operate decompress - var result = await FilesystemTasks.Wrap(() => - StorageArchiveService.DecompressAsync(archive.Path, destinationFolder?.Path ?? string.Empty, password, encoding)); - - if (decompressArchiveViewModel.OpenDestinationFolderOnCompletion) - await NavigationHelpers.OpenPath(destinationFolderPath, context.ShellPage, FilesystemItemType.Directory); - } - - protected override bool CanDecompressInsideArchive() - { - return - context.PageType == ContentPageTypes.ZipFolder && - !context.HasSelection && - context.Folder is not null && - FileExtensionHelpers.IsZipFile(Path.GetExtension(context.Folder.ItemPath)); - } - - protected override bool CanDecompressSelectedItems() - { - return context.SelectedItems.Count == 1 && base.CanDecompressSelectedItems(); - } - - private string? GetArchivePath() - { - if (!string.IsNullOrEmpty(context.SelectedItem?.ItemPath)) - return context.SelectedItem?.ItemPath; - - if (context.PageType == ContentPageTypes.ZipFolder && !context.HasSelection) - return context.Folder?.ItemPath; - - return null; - } - - private void SaveExtractionLocation(string path) - { - var previousArchiveExtractionLocations = UserSettingsService.GeneralSettingsService.PreviousArchiveExtractionLocations?.ToList() ?? []; - previousArchiveExtractionLocations.Remove(path); - previousArchiveExtractionLocations.Insert(0, path); - - if (previousArchiveExtractionLocations.Count > 10) - UserSettingsService.GeneralSettingsService.PreviousArchiveExtractionLocations = previousArchiveExtractionLocations.RemoveFrom(11); - else - UserSettingsService.GeneralSettingsService.PreviousArchiveExtractionLocations = previousArchiveExtractionLocations; - } - } -} diff --git a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.cs b/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.cs index 7d0ea689933d..53d9f499f73f 100644 --- a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.cs +++ b/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchive.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.App.Dialogs; using Files.Shared.Helpers; using Microsoft.UI.Xaml.Controls; @@ -133,4 +132,3 @@ private void SaveExtractionLocation(string path) } } -#endif diff --git a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.Windows.cs b/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.Windows.cs deleted file mode 100644 index a730c4ea548d..000000000000 --- a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.Windows.cs +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Dialogs; -using Microsoft.UI.Xaml.Controls; -using System.Text; -using Windows.Foundation.Metadata; -using Windows.Storage; - -namespace Files.App.Actions -{ - [GeneratedRichCommand] - internal sealed partial class DecompressArchiveToChildFolderAction : BaseDecompressArchiveAction - { - public override string Label - => ComputeLabel(); - - public override string Description - => Strings.DecompressArchiveToChildFolderDescription.GetLocalizedFormatResource(context.SelectedItems.Count); - - public string AccessKey - => "C"; - - public DecompressArchiveToChildFolderAction() - { - } - - public override async Task ExecuteAsync(object? parameter = null) - { - if (context.SelectedItems.Count is 0) - return; - - foreach (var selectedItem in context.SelectedItems) - { - var password = string.Empty; - - var archive = await StorageHelpers.ToStorageItem(selectedItem.ItemPath!); - var currentFolderPath = context.ShellPage?.ShellViewModel?.CurrentFolder?.ItemPath; - if (archive?.Path is null) - return; - - var currentFolder = await StorageHelpers.ToStorageItem(currentFolderPath ?? string.Empty); - - if (await FilesystemTasks.Wrap(() => StorageArchiveService.IsEncryptedAsync(archive.Path))) - { - DecompressArchiveDialogViewModel decompressArchiveViewModel = new(archive) - { - IsArchiveEncrypted = true, - ShowPathSelection = false - }; - DecompressArchiveDialog decompressArchiveDialog = new() { ViewModel = decompressArchiveViewModel }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - decompressArchiveDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - ContentDialogResult option = await decompressArchiveDialog.TryShowAsync(); - if (option != ContentDialogResult.Primary) - return; - - password = Encoding.UTF8.GetString(decompressArchiveViewModel.Password!); - } - - BaseStorageFolder? destinationFolder = null; - if (currentFolder is not null) - { - var destinationResult = await FilesystemTasks.WrapNullable(() => - currentFolder.CreateFolderAsync(SystemIO.Path.GetFileNameWithoutExtension(archive.Path), CreationCollisionOption.GenerateUniqueName).AsTask()); - destinationFolder = destinationResult.Result; - } - - // Operate decompress - await FilesystemTasks.Wrap(() => - StorageArchiveService.DecompressAsync(selectedItem.ItemPath!, destinationFolder?.Path ?? string.Empty, password)); - } - } - - protected override void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) - { - switch (e.PropertyName) - { - case nameof(IContentPageContext.SelectedItems): - case nameof(IContentPageContext.Folder): - { - if (IsContextPageTypeAdaptedToCommand()) - { - OnPropertyChanged(nameof(Label)); - OnPropertyChanged(nameof(IsExecutable)); - } - - break; - } - } - } - - private string ComputeLabel() - => ToPlatformSeparator(ComputeLabelCore()); - - private static string ToPlatformSeparator(string label) - => SystemIO.Path.DirectorySeparatorChar == '\\' ? label : label.Replace('\\', SystemIO.Path.DirectorySeparatorChar); - - private string ComputeLabelCore() - { - if (context.SelectedItems == null || context.SelectedItems.Count == 0) - return string.Format(Strings.BaseLayoutItemContextFlyoutExtractToChildFolder.GetLocalizedResource(), string.Empty); - - return context.SelectedItems.Count > 1 - ? string.Format(Strings.BaseLayoutItemContextFlyoutExtractToChildFolder.GetLocalizedResource(), "*") - : string.Format(Strings.BaseLayoutItemContextFlyoutExtractToChildFolder.GetLocalizedResource(), SystemIO.Path.GetFileNameWithoutExtension(context.SelectedItems.First().Name)); - } - } -} diff --git a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.cs b/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.cs index 8036eb252ea0..7d84d0f93377 100644 --- a/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.cs +++ b/src/Files.App/Actions/Content/Archives/Decompress/DecompressArchiveToChildFolderAction.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.App.Dialogs; using Microsoft.UI.Xaml.Controls; using System.Text; @@ -103,4 +102,3 @@ private string ComputeLabelCore() } } -#endif diff --git a/src/Files.App/Actions/Content/Install/InstallCertificateAction.Windows.cs b/src/Files.App/Actions/Content/Install/InstallCertificateAction.Windows.cs deleted file mode 100644 index d714f5a0e590..000000000000 --- a/src/Files.App/Actions/Content/Install/InstallCertificateAction.Windows.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; - -namespace Files.App.Actions -{ - internal sealed partial class InstallCertificateAction : ObservableObject, IAction - { - public async Task ExecuteAsync(object? parameter = null) - { - await ContextMenu.InvokeVerb("add", context.SelectedItems.Select(x => x.ItemPath).ToArray()); - } - } -} diff --git a/src/Files.App/Actions/Content/Install/InstallCertificateAction.cs b/src/Files.App/Actions/Content/Install/InstallCertificateAction.cs index 7c23850cb87e..da617be1983d 100644 --- a/src/Files.App/Actions/Content/Install/InstallCertificateAction.cs +++ b/src/Files.App/Actions/Content/Install/InstallCertificateAction.cs @@ -36,11 +36,9 @@ public InstallCertificateAction() context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(install): this Windows command is hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/Content/Install/InstallFontAction.cs b/src/Files.App/Actions/Content/Install/InstallFontAction.cs index 36e857ce2965..2e18c62e3748 100644 --- a/src/Files.App/Actions/Content/Install/InstallFontAction.cs +++ b/src/Files.App/Actions/Content/Install/InstallFontAction.cs @@ -49,11 +49,7 @@ public async Task ExecuteAsync(object? parameter = null) var paths = context.SelectedItems.Select(item => item.ItemPath!).ToArray(); var outcome = ReturnResult.Success; var installed = (long)context.SelectedItems.Count; -#if WINDOWS - await Win32Helper.InstallFontsAsync(paths, false); -#else (outcome, installed) = await InstallForCurrentUserAsync(paths); -#endif StatusCenterViewModel.RemoveItem(banner); var currentWorkingDirectory = context.ShellPage.GetRequiredShellViewModel().WorkingDirectory!; diff --git a/src/Files.App/Actions/Content/Install/InstallInfDriverAction.Windows.cs b/src/Files.App/Actions/Content/Install/InstallInfDriverAction.Windows.cs deleted file mode 100644 index 8337e323691b..000000000000 --- a/src/Files.App/Actions/Content/Install/InstallInfDriverAction.Windows.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; - -namespace Files.App.Actions -{ - internal sealed partial class InstallInfDriverAction : ObservableObject, IAction - { - public async Task ExecuteAsync(object? parameter = null) - { - await Task.WhenAll(context.SelectedItems.Select(selectedItem => Win32Helper.InstallInf(selectedItem.ItemPath))); - } - } -} diff --git a/src/Files.App/Actions/Content/Install/InstallInfDriverAction.cs b/src/Files.App/Actions/Content/Install/InstallInfDriverAction.cs index a21b475ac73c..795f913e3231 100644 --- a/src/Files.App/Actions/Content/Install/InstallInfDriverAction.cs +++ b/src/Files.App/Actions/Content/Install/InstallInfDriverAction.cs @@ -36,11 +36,9 @@ public InstallInfDriverAction() context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(install): this Windows command is hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif public void Context_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/Content/Run/BaseRunAsAction.Windows.cs b/src/Files.App/Actions/Content/Run/BaseRunAsAction.Windows.cs deleted file mode 100644 index 04cf7f80f29c..000000000000 --- a/src/Files.App/Actions/Content/Run/BaseRunAsAction.Windows.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - - - -namespace Files.App.Actions -{ - internal abstract partial class BaseRunAsAction : ObservableObject, IAction - { - public async Task ExecuteAsync(object? parameter = null) - { - await ContextMenu.InvokeVerb(_verb, _context.SelectedItem!.ItemPath); - } - } -} diff --git a/src/Files.App/Actions/Content/Run/BaseRunAsAction.cs b/src/Files.App/Actions/Content/Run/BaseRunAsAction.cs index 70ad7c51d1e8..981e1ec6c575 100644 --- a/src/Files.App/Actions/Content/Run/BaseRunAsAction.cs +++ b/src/Files.App/Actions/Content/Run/BaseRunAsAction.cs @@ -28,11 +28,9 @@ public BaseRunAsAction(string verb) _context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(launching): Windows shell elevation verbs are hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif public void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/Content/Run/RunWithPowershellAction.Windows.cs b/src/Files.App/Actions/Content/Run/RunWithPowershellAction.Windows.cs deleted file mode 100644 index 5f27a9a5f12f..000000000000 --- a/src/Files.App/Actions/Content/Run/RunWithPowershellAction.Windows.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; - -namespace Files.App.Actions -{ - internal sealed partial class RunWithPowershellAction : ObservableObject, IAction - { - public Task ExecuteAsync(object? parameter = null) - { - var itemPath = context.ShellPage?.SlimContentPage?.SelectedItem?.ItemPath; - return Win32Helper.RunPowershellCommandAsync( - $"& {Win32Helper.ToPowerShellStringLiteral(itemPath)}", - PowerShellExecutionOptions.None, - context.Folder?.ItemPath - ); - } - } -} diff --git a/src/Files.App/Actions/Content/Run/RunWithPowershellAction.cs b/src/Files.App/Actions/Content/Run/RunWithPowershellAction.cs index 83e77db69d73..ff8ea006f1fd 100644 --- a/src/Files.App/Actions/Content/Run/RunWithPowershellAction.cs +++ b/src/Files.App/Actions/Content/Run/RunWithPowershellAction.cs @@ -35,11 +35,9 @@ public RunWithPowershellAction() context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(launching): this Windows command is hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/FileSystem/CopyItemFromHomeAction.cs b/src/Files.App/Actions/FileSystem/CopyItemFromHomeAction.cs index 048aa65ffbb8..1b5cc46376b4 100644 --- a/src/Files.App/Actions/FileSystem/CopyItemFromHomeAction.cs +++ b/src/Files.App/Actions/FileSystem/CopyItemFromHomeAction.cs @@ -63,15 +63,6 @@ public async Task ExecuteAsync(object? parameter = null) return; } -#if WINDOWS - if (storageItem is SystemStorageFolder or SystemStorageFile) - { - var standardItems = await new[] { storageItem }.ToStandardStorageItemsAsync(); - if (standardItems.Any()) - storageItem = standardItems.First(); - } - -#endif dataPackage.Properties.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; dataPackage.SetStorageItems(new[] { storageItem }, false); diff --git a/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.Windows.cs b/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.Windows.cs deleted file mode 100644 index 3e4030c2da29..000000000000 --- a/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.Windows.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.UI.Xaml.Controls; -using Windows.Foundation.Metadata; - -namespace Files.App.Actions -{ - internal sealed partial class CreateAlternateDataStreamAction : BaseUIAction, IAction - { - public async Task ExecuteAsync(object? parameter = null) - { - var nameDialog = DynamicDialogFactory.GetFor_CreateAlternateDataStreamDialog(); - await nameDialog.TryShowAsync(); - - if (nameDialog.DynamicResult != DynamicDialogResult.Primary) - return; - - var userInput = nameDialog.ViewModel.AdditionalData as string; - await Task.WhenAll(context.SelectedItems.Select(async selectedItem => - { - var itemPath = selectedItem.ItemPath!; - var isDateOk = Win32Helper.GetFileDateModified(itemPath, out var dateModified); - var isReadOnly = Win32Helper.HasFileAttribute(itemPath, System.IO.FileAttributes.ReadOnly); - - // Unset read-only attribute (#7534) - if (isReadOnly) - Win32Helper.UnsetFileAttribute(itemPath, System.IO.FileAttributes.ReadOnly); - - if (!Win32Helper.WriteStringToFile($"{itemPath}:{userInput}", "")) - { - var dialog = new ContentDialog - { - Title = Strings.ErrorCreatingDataStreamTitle.GetLocalizedResource(), - Content = Strings.ErrorCreatingDataStreamDescription.GetLocalizedResource(), - PrimaryButtonText = "Ok".GetLocalizedResource() - }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - dialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - await dialog.TryShowAsync(); - } - - // Restore read-only attribute (#7534) - if (isReadOnly) - Win32Helper.SetFileAttribute(itemPath, System.IO.FileAttributes.ReadOnly); - - // Restore date modified - if (isDateOk) - Win32Helper.SetFileDateModified(itemPath, dateModified); - })); - - if (context.ShellPage is null) - return; - - if (FoldersSettingsService.AreAlternateStreamsVisible) - await context.ShellPage.Refresh_Click(); - else if (ApplicationSettingsService.ShowDataStreamsAreHiddenPrompt) - { - var dialog = new ContentDialog - { - Title = Strings.DataStreamsAreHiddenTitle.GetLocalizedResource(), - Content = Strings.DataStreamsAreHiddenDescription.GetLocalizedResource(), - PrimaryButtonText = Strings.Yes.GetLocalizedResource(), - SecondaryButtonText = Strings.DontShowAgain.GetLocalizedResource() - }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - dialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - var result = await dialog.TryShowAsync(); - if (result == ContentDialogResult.Primary) - { - FoldersSettingsService.AreAlternateStreamsVisible = true; - await context.ShellPage.Refresh_Click(); - } - else - ApplicationSettingsService.ShowDataStreamsAreHiddenPrompt = false; - } - } - } -} diff --git a/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.cs b/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.cs index 8221b90df10c..ff6bea8a337b 100644 --- a/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.cs +++ b/src/Files.App/Actions/FileSystem/CreateAlternateDataStreamAction.cs @@ -39,11 +39,9 @@ public CreateAlternateDataStreamAction() context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(streams): this Windows command is hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs b/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs index 8e0939f003ae..4613eb121dd7 100644 --- a/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs +++ b/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs @@ -58,11 +58,7 @@ await confirmationDialog.TryShowAsync() is ContentDialogResult.Primary) { var banner = StatusCenterHelper.AddCard_EmptyRecycleBin(ReturnResult.InProgress); -#if WINDOWS - bool result = await STATask.Run(StorageTrashBinService.EmptyTrashBin, App.Logger); -#else bool result = await Task.Run(StorageTrashBinService.EmptyTrashBin); -#endif StatusCenterViewModel.RemoveItem(banner); diff --git a/src/Files.App/Actions/FileSystem/FormatDriveAction.cs b/src/Files.App/Actions/FileSystem/FormatDriveAction.cs index a91db1d67b34..15a01d6fd1be 100644 --- a/src/Files.App/Actions/FileSystem/FormatDriveAction.cs +++ b/src/Files.App/Actions/FileSystem/FormatDriveAction.cs @@ -43,18 +43,10 @@ public virtual Task ExecuteAsync(object? parameter = null) // Windows opens the shell format dialog; Linux opens GNOME Disks or KDE Partition Manager when one is installed (else the command is hidden) protected static bool IsFormatAvailable(string? path) -#if !WINDOWS => DriveHelpers.CanFormat(path); -#else - => true; -#endif protected static Task FormatDrive(string? path) -#if !WINDOWS => DriveHelpers.OpenFormatDialogAsync(path); -#else - => Win32Helper.OpenFormatDriveDialog(path ?? string.Empty); -#endif public void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/Open/EditInNotepadAction.Windows.cs b/src/Files.App/Actions/Open/EditInNotepadAction.Windows.cs deleted file mode 100644 index 08f864806a27..000000000000 --- a/src/Files.App/Actions/Open/EditInNotepadAction.Windows.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; - -namespace Files.App.Actions -{ - internal sealed partial class EditInNotepadAction : ObservableObject, IAction - { - public Task ExecuteAsync(object? parameter = null) - { - return Task.WhenAll(context.SelectedItems.Select(item => Win32Helper.RunPowershellCommandAsync($"& 'notepad.exe' {Win32Helper.ToPowerShellStringLiteral(item.ItemPath)}", PowerShellExecutionOptions.Hidden))); - } - } -} diff --git a/src/Files.App/Actions/Open/EditInNotepadAction.cs b/src/Files.App/Actions/Open/EditInNotepadAction.cs index 25b5061b4d91..17fb5451c2fd 100644 --- a/src/Files.App/Actions/Open/EditInNotepadAction.cs +++ b/src/Files.App/Actions/Open/EditInNotepadAction.cs @@ -36,11 +36,9 @@ public EditInNotepadAction() context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(launching): this Windows command is hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) { diff --git a/src/Files.App/Actions/Open/OpenClassicPropertiesAction.Windows.cs b/src/Files.App/Actions/Open/OpenClassicPropertiesAction.Windows.cs deleted file mode 100644 index 52f9d1551189..000000000000 --- a/src/Files.App/Actions/Open/OpenClassicPropertiesAction.Windows.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.UI.Shell; - -namespace Files.App.Actions -{ - internal sealed partial class OpenClassicPropertiesAction : ObservableObject, IAction - { - public Task ExecuteAsync(object? parameter = null) - { - if (context.HasSelection && context?.SelectedItem?.ItemPath is not null) - ExecuteShellCommand(context.SelectedItem.ItemPath); - else if (context?.Folder?.ItemPath is not null) - ExecuteShellCommand(context.Folder.ItemPath); - - return Task.CompletedTask; - } - - private unsafe void ExecuteShellCommand(string itemPath) - { - SHELLEXECUTEINFOW info = default; - info.cbSize = (uint)Marshal.SizeOf(info); - info.nShow = 5; // SW_SHOW - info.fMask = 0x0000000C; // SEE_MASK_INVOKEIDLIST - - fixed (char* cVerb = "properties", lpFile = itemPath) - { - info.lpVerb = cVerb; - info.lpFile = lpFile; - - PInvoke.ShellExecuteEx(ref info); - } - } - } -} diff --git a/src/Files.App/Actions/Open/OpenClassicPropertiesAction.cs b/src/Files.App/Actions/Open/OpenClassicPropertiesAction.cs index f52f3d13bea8..5e5e77fb3606 100644 --- a/src/Files.App/Actions/Open/OpenClassicPropertiesAction.cs +++ b/src/Files.App/Actions/Open/OpenClassicPropertiesAction.cs @@ -41,11 +41,9 @@ public OpenClassicPropertiesAction() context.PropertyChanged += Context_PropertyChanged; } -#if !WINDOWS // LINUX-TODO(properties): the Windows shell properties command is hidden on Linux. public Task ExecuteAsync(object? parameter = null) => Task.CompletedTask; -#endif private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) diff --git a/src/Files.App/Actions/Open/OpenInIDEAction.cs b/src/Files.App/Actions/Open/OpenInIDEAction.cs index 6a6ba511aa0c..0734ac68b252 100644 --- a/src/Files.App/Actions/Open/OpenInIDEAction.cs +++ b/src/Files.App/Actions/Open/OpenInIDEAction.cs @@ -51,15 +51,6 @@ public async Task ExecuteAsync(object? parameter = null) return; } -#if WINDOWS - var res = await Win32Helper.RunPowershellCommandAsync( - $"& {Win32Helper.ToPowerShellStringLiteral(_devToolsSettingsService.IDEPath)} {Win32Helper.ToPowerShellStringLiteral(workingDirectory)}", - PowerShellExecutionOptions.Hidden - ); - - if (!res) - await DynamicDialogFactory.ShowFor_IDEErrorDialog(_devToolsSettingsService.IDEName); -#endif } private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) diff --git a/src/Files.App/Actions/Open/OpenRepoInIDEAction.cs b/src/Files.App/Actions/Open/OpenRepoInIDEAction.cs index e7653a00be76..c4d5589c1200 100644 --- a/src/Files.App/Actions/Open/OpenRepoInIDEAction.cs +++ b/src/Files.App/Actions/Open/OpenRepoInIDEAction.cs @@ -34,15 +34,6 @@ public OpenRepoInIDEAction() public async Task ExecuteAsync(object? parameter = null) { -#if WINDOWS - var res = await Win32Helper.RunPowershellCommandAsync( - $"& {Win32Helper.ToPowerShellStringLiteral(_devToolsSettingsService.IDEPath)} {Win32Helper.ToPowerShellStringLiteral(_context.ShellPage!.InstanceViewModel.GitRepositoryPath)}", - PowerShellExecutionOptions.Hidden - ); - - if (!res) - await DynamicDialogFactory.ShowFor_IDEErrorDialog(_devToolsSettingsService.IDEName); -#else var path = _context.ShellPage?.InstanceViewModel.GitRepositoryPath; if (!SystemIO.Path.IsPathRooted(path)) return; @@ -51,7 +42,6 @@ public async Task ExecuteAsync(object? parameter = null) .StartAsync(_devToolsSettingsService.IDEPath, [path]); if (!launched) await DynamicDialogFactory.ShowFor_IDEErrorDialog(_devToolsSettingsService.IDEName); -#endif } private void Context_PropertyChanged(object? sender, PropertyChangedEventArgs e) diff --git a/src/Files.App/Actions/Open/OpenSettingsFileAction.cs b/src/Files.App/Actions/Open/OpenSettingsFileAction.cs index 567fad8b7732..94007495e874 100644 --- a/src/Files.App/Actions/Open/OpenSettingsFileAction.cs +++ b/src/Files.App/Actions/Open/OpenSettingsFileAction.cs @@ -32,12 +32,7 @@ public async Task ExecuteAsync(object? parameter = null) try { var settingsJsonFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appdata:///local/{Constants.LocalSettings.SettingsFolderName}/{Constants.LocalSettings.UserSettingsFileName}")); -#if WINDOWS - if (!await Launcher.LaunchFileAsync(settingsJsonFile)) - await ContextMenu.InvokeVerb("open", settingsJsonFile.Path); -#else await NavigationHelpers.OpenFileLinuxAsync(settingsJsonFile.Path); -#endif } catch (Exception ex) { diff --git a/src/Files.App/Actions/Open/OpenTerminalAction.Windows.cs b/src/Files.App/Actions/Open/OpenTerminalAction.Windows.cs deleted file mode 100644 index 0915dcca46f9..000000000000 --- a/src/Files.App/Actions/Open/OpenTerminalAction.Windows.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; -using Windows.Storage; -using Windows.Win32; -using Windows.Win32.System.Com; - -namespace Files.App.Actions -{ - internal partial class OpenTerminalAction : ObservableObject, IAction - { - // DelegationTerminal CLSIDs registered by Windows Terminal. When one of these - // is the user's default, launching wt.exe gives the user's chosen profile and - // supports multi-tab. Source: microsoft/terminal policies/WindowsTerminal.admx. - private static readonly Guid[] WindowsTerminalDelegationClsids = - [ - new([0x52, 0xFF, 0x2C, 0xE1, 0x66, 0xA8, 0x77, 0x4C, 0x9A, 0x90, 0xF5, 0x70, 0xA7, 0xAA, 0x2C, 0x6B]), // Windows Terminal (stable) - new([0x1F, 0x3F, 0x63, 0x86, 0x54, 0x64, 0xEC, 0x40, 0x89, 0xCE, 0xDA, 0x4E, 0xBA, 0x97, 0x7E, 0xE2]), // Windows Terminal Preview - ]; - - - protected virtual ProcessStartInfo? GetProcessStartInfo(string[] paths) - { - if (paths.Length is 0) - return null; - - if (IsWindowsTerminalDefault()) - { - var startInfo = new ProcessStartInfo - { - FileName = "wt.exe", - UseShellExecute = false, - ArgumentList = { "-d", paths[0] } - }; - - for (int i = 1; i < paths.Length; i++) - { - startInfo.ArgumentList.Add(";"); - startInfo.ArgumentList.Add("nt"); - startInfo.ArgumentList.Add("-d"); - startInfo.ArgumentList.Add(paths[i]); - } - - return startInfo; - } - - // Launch cmd.exe when Windows Terminal is not the effective default host. - return new() - { - FileName = "cmd.exe", - WorkingDirectory = paths[0], - UseShellExecute = true - }; - } - - private static unsafe bool IsWindowsTerminalDefault() - { - try - { - using var key = Registry.CurrentUser.OpenSubKey(@"Console\%%Startup"); - var consoleClsid = Guid.TryParse(key?.GetValue("DelegationConsole") as string, out var consoleClsidResult) ? consoleClsidResult : Guid.Empty; - var terminalClsid = Guid.TryParse(key?.GetValue("DelegationTerminal") as string, out var terminalClsidResult) ? terminalClsidResult : Guid.Empty; - - // Windows treats either missing or zero CLSID as "Let Windows decide". - if (consoleClsid == Guid.Empty || terminalClsid == Guid.Empty) - { - // Windows 11 22H2 introduced Terminal as the automatic default. - if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22621)) - return false; - - // Match conhost's IDefaultTerminalMarker probe on the stable console server. - // Source: microsoft/terminal src/server/IoDispatchers.cpp. - consoleClsid = new([0x47, 0xA9, 0xAC, 0x2E, 0x5F, 0x7F, 0xFA, 0x4C, 0xBA, 0x87, 0x8F, 0x7F, 0xBE, 0xEF, 0xBE, 0x69]); - Guid markerIid = new([0xC0, 0x6B, 0x6E, 0x74, 0x05, 0xAB, 0x38, 0x4E, 0xAB, 0x14, 0x71, 0xE8, 0x67, 0x63, 0x14, 0x1F]); - var result = PInvoke.CoCreateInstance(&consoleClsid, null, CLSCTX.CLSCTX_LOCAL_SERVER, &markerIid, out var marker); - return result.Succeeded && marker is not null; - } - - return consoleClsid != new Guid([0xC0, 0x10, 0x3D, 0xB2, 0x2E, 0xE5, 0x1E, 0x41, 0x9D, 0x5B, 0xC0, 0x9F, 0xDF, 0x70, 0x9C, 0x7D]) - && WindowsTerminalDelegationClsids.Contains(terminalClsid); - } - catch - { - } - - return false; - } - } -} diff --git a/src/Files.App/Actions/Open/OpenTerminalAction.cs b/src/Files.App/Actions/Open/OpenTerminalAction.cs index ed64ef6a2804..13d9113ab050 100644 --- a/src/Files.App/Actions/Open/OpenTerminalAction.cs +++ b/src/Files.App/Actions/Open/OpenTerminalAction.cs @@ -13,11 +13,7 @@ internal partial class OpenTerminalAction : ObservableObject, IAction public virtual string Label -#if WINDOWS - => Strings.OpenTerminal.GetLocalizedResource(); -#else => Strings.OpenTerminalLinux.GetLocalizedResource(); -#endif public virtual string Description => Strings.OpenTerminalDescription.GetLocalizedResource(); @@ -50,36 +46,15 @@ public Task ExecuteAsync(object? parameter = null) if (paths.Length is 0) return Task.CompletedTask; -#if !WINDOWS return OpenLinuxTerminalsAsync(paths); -#else - var terminalStartInfo = GetProcessStartInfo(paths); - if (terminalStartInfo is null) - return Task.CompletedTask; - - MainWindow.Instance.DispatcherQueue.TryEnqueue(() => - { - try - { - Process.Start(terminalStartInfo); - } - catch (Win32Exception) - { - } - }); - - return Task.CompletedTask; -#endif } -#if !WINDOWS private static async Task OpenLinuxTerminalsAsync(string[] paths) { var launcher = Ioc.Default.GetRequiredService(); foreach (var path in paths) await launcher.OpenTerminalAsync(path); } -#endif diff --git a/src/Files.App/Actions/Open/OpenTerminalAsAdminAction.cs b/src/Files.App/Actions/Open/OpenTerminalAsAdminAction.cs index 4cd69845f982..a367a6a2832f 100644 --- a/src/Files.App/Actions/Open/OpenTerminalAsAdminAction.cs +++ b/src/Files.App/Actions/Open/OpenTerminalAsAdminAction.cs @@ -7,11 +7,7 @@ namespace Files.App.Actions internal sealed partial class OpenTerminalAsAdminAction : OpenTerminalAction { public override string Label -#if WINDOWS - => Strings.OpenTerminalAsAdmin.GetLocalizedResource(); -#else => Strings.OpenTerminalAsAdminLinux.GetLocalizedResource(); -#endif public override string Description => Strings.OpenTerminalAsAdminDescription.GetLocalizedResource(); @@ -22,18 +18,5 @@ public override HotKey HotKey public override bool IsExecutable => OperatingSystem.IsWindows() && base.IsExecutable; -#if WINDOWS - protected override ProcessStartInfo? GetProcessStartInfo(string[] paths) - { - var startInfo = base.GetProcessStartInfo(paths); - if (startInfo is not null) - { - startInfo.Verb = "runas"; - startInfo.UseShellExecute = true; - } - - return startInfo; - } -#endif } } diff --git a/src/Files.App/Actions/Open/OpenTerminalFromHomeAction.cs b/src/Files.App/Actions/Open/OpenTerminalFromHomeAction.cs index c7a8b70e6b4e..bce11d9f8ca8 100644 --- a/src/Files.App/Actions/Open/OpenTerminalFromHomeAction.cs +++ b/src/Files.App/Actions/Open/OpenTerminalFromHomeAction.cs @@ -9,11 +9,7 @@ internal sealed partial class OpenTerminalFromHomeAction : OpenTerminalAction private IHomePageContext HomePageContext { get; } = Ioc.Default.GetRequiredService(); public override string Label -#if WINDOWS - => Strings.OpenTerminal.GetLocalizedResource(); -#else => Strings.OpenTerminalLinux.GetLocalizedResource(); -#endif public override string Description => Strings.OpenTerminalDescription.GetLocalizedResource(); diff --git a/src/Files.App/Actions/Open/OpenTerminalFromSidebarAction.cs b/src/Files.App/Actions/Open/OpenTerminalFromSidebarAction.cs index 471ae8a85550..56c4a16facf5 100644 --- a/src/Files.App/Actions/Open/OpenTerminalFromSidebarAction.cs +++ b/src/Files.App/Actions/Open/OpenTerminalFromSidebarAction.cs @@ -9,11 +9,7 @@ internal sealed partial class OpenTerminalFromSidebarAction : OpenTerminalAction private ISidebarContext SidebarContext { get; } = Ioc.Default.GetRequiredService(); public override string Label -#if WINDOWS - => Strings.OpenTerminal.GetLocalizedResource(); -#else => Strings.OpenTerminalLinux.GetLocalizedResource(); -#endif public override string Description => Strings.OpenTerminalDescription.GetLocalizedResource(); diff --git a/src/Files.App/Actions/Sidebar/CopyItemFromSidebarAction.cs b/src/Files.App/Actions/Sidebar/CopyItemFromSidebarAction.cs index 27415b998e33..39ef9e5a01b7 100644 --- a/src/Files.App/Actions/Sidebar/CopyItemFromSidebarAction.cs +++ b/src/Files.App/Actions/Sidebar/CopyItemFromSidebarAction.cs @@ -63,15 +63,6 @@ public async Task ExecuteAsync(object? parameter = null) return; } -#if WINDOWS - if (storageItem is SystemStorageFolder or SystemStorageFile) - { - var standardItems = await new[] { storageItem }.ToStandardStorageItemsAsync(); - if (standardItems.Any()) - storageItem = standardItems.First(); - } - -#endif dataPackage.Properties.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; dataPackage.SetStorageItems(new[] { storageItem }, false); diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index c414d743f742..ad549b14907b 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -8,10 +8,6 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; -#if WINDOWS -using Microsoft.Windows.AppLifecycle; -using Windows.Win32; -#endif using System.Runtime; using Windows.ApplicationModel; using Windows.ApplicationModel.DataTransfer; @@ -25,9 +21,6 @@ namespace Files.App /// public partial class App : Application { -#if WINDOWS - public static SystemTrayIcon? SystemTrayIcon { get; private set; } -#endif public static TaskCompletionSource? SplashScreenLoadingTCS { get; private set; } public static string? OutputPath { get; set; } @@ -66,10 +59,8 @@ public App() AppLifecycleHelper.RecordFirstChanceExceptions(); UnhandledException += (sender, e) => { -#if !WINDOWS if (DesktopRuntimeGuards.TryHandleRecoverable(e)) return; -#endif AppLifecycleHelper.HandleAppUnhandledException(e.Exception, true, "Application.UnhandledException", e.Message); }; AppDomain.CurrentDomain.UnhandledException += (sender, e) => AppLifecycleHelper.HandleAppUnhandledException(e.ExceptionObject as Exception, false, "AppDomain.UnhandledException"); @@ -80,442 +71,11 @@ public App() }; AppDomain.CurrentDomain.ProcessExit += static (_, _) => SafetyExtensions.IgnoreExceptions(() => Ioc.Default.GetService()?.TryCompleteAndFlush(TimeSpan.FromSeconds(2))); -#if !WINDOWS AppDomain.CurrentDomain.ProcessExit += static (_, _) => FileTagsHelper.DrainPendingWritesAsync().GetAwaiter().GetResult(); AppDomain.CurrentDomain.ProcessExit += static (_, _) => SafetyExtensions.IgnoreExceptions(ArchiveOpenTempStore.CleanupCurrentProcess); _ = Task.Run(ArchiveOpenTempStore.CleanupStale); -#endif } -#if WINDOWS - /// - /// Gets invoked when the application is launched normally by the end user. - /// - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - UiDispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); - - // Constructed on the UI thread: the ctor subscribes the UI-thread-only Clipboard.ContentChanged - AppModel = new AppModel(); - - _ = ActivateAsync(); - - async Task ActivateAsync() - { - // Build the DI container off-thread while the window initializes - var appModel = AppModel; - Task commandsWarmupTask = Task.CompletedTask; - var servicesTask = Task.Run(() => - { - try - { - var provider = AppLifecycleHelper.ConfigureHost(appModel); - - // Configure Ioc here so Ioc.Default-dependent constructions warm off-thread too - Ioc.Default.ConfigureServices(provider); - - // Load the appearance settings needed for the first frame off the UI thread. - _ = provider.GetRequiredService().LeaveAppRunning; - var appearanceSettings = provider.GetRequiredService(); - _ = appearanceSettings.AppThemeMode; - _ = appearanceSettings.AppThemeBackdropMaterial; - - // Commands are needed for the main page, not for the initial window and backdrop. - commandsWarmupTask = Task.Run(() => - { - var previousPriority = Thread.CurrentThread.Priority; - Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; - try - { - // Action and context constructors access these statics. - QuickAccessManager = provider.GetRequiredService(); - HistoryWrapper = provider.GetRequiredService(); - FileTagsManager = provider.GetRequiredService(); - LibraryManager = provider.GetRequiredService(); - - _ = provider.GetRequiredService(); - } - catch (Exception) - { - // UI-thread-only constructors run on first use instead. - } - finally - { - Thread.CurrentThread.Priority = previousPriority; - } - }); - - return provider; - } - catch (Exception) - { - // A UI-thread-only service ctor failed off-thread; rebuilt on the UI thread below - return null; - } - }); - - // Get AppActivationArguments - var appActivationArguments = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs(); - var isStartupTask = appActivationArguments.Data is Windows.ApplicationModel.Activation.IStartupTaskActivatedEventArgs; - - // IsDynamicCodeSupported is false on Native AOT, where startup is fast enough to skip the splash screen - var showSplashScreen = System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported; - - if (!isStartupTask) - { - // Construct the window while appearance settings are loaded. - _ = MainWindow.Instance; - } - - // Configure the DI (dependency injection) container - var serviceProvider = await servicesTask; - if (serviceProvider is null) - { - serviceProvider = AppLifecycleHelper.ConfigureHost(appModel); - Ioc.Default.ConfigureServices(serviceProvider); - } - - var userSettingsService = Ioc.Default.GetRequiredService(); - var isLeaveAppRunning = userSettingsService.GeneralSettingsService.LeaveAppRunning; - - if (!isStartupTask || !isLeaveAppRunning) - { - if (showSplashScreen) - { - SplashScreenLoadingTCS = new TaskCompletionSource(); - MainWindow.Instance.ShowSplashScreen(); - } - - if (!await MainWindow.Instance.ActivateWithBackdropAsync()) - return; - } - - await commandsWarmupTask; - - // Configure Sentry - if (AppLifecycleHelper.AppEnvironment is not AppEnvironment.Dev) - AppLifecycleHelper.ConfigureSentry(); - - // TODO: Replace with DI - QuickAccessManager = Ioc.Default.GetRequiredService(); - HistoryWrapper = Ioc.Default.GetRequiredService(); - FileTagsManager = Ioc.Default.GetRequiredService(); - LibraryManager = Ioc.Default.GetRequiredService(); - Logger = Ioc.Default.GetRequiredService>(); - AppModel = Ioc.Default.GetRequiredService(); - - // Hook events for the window - MainWindow.Instance.Closed += Window_Closed; - MainWindow.Instance.Activated += Window_Activated; - - Logger.LogInformation($"App launched. Launch args type: {appActivationArguments.Data.GetType().Name}"); - - if (!(isStartupTask && isLeaveAppRunning)) - { - if (SplashScreenLoadingTCS is not null) - { - // Wait for the UI to update - await SplashScreenLoadingTCS.Task.WithTimeoutAsync(TimeSpan.FromMilliseconds(500)); - SplashScreenLoadingTCS = null; - } - - // Deferred so the first frame renders first - MainWindow.Instance.DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () => - { - SystemTrayIcon = new SystemTrayIcon(); - if (userSettingsService.GeneralSettingsService.ShowSystemTrayIcon) - SystemTrayIcon.Show(); - }); - - _ = MainWindow.Instance.InitializeApplicationAsync(appActivationArguments.Data); - } - else - { - // Create a system tray icon - SystemTrayIcon = new SystemTrayIcon(); - if (userSettingsService.GeneralSettingsService.ShowSystemTrayIcon) - SystemTrayIcon.Show(); - - // Sleep current instance - var pool = new Semaphore(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance"); - Program.Pool = pool; - - var cts = new CancellationTokenSource(); - TryEmptyWorkingSetWhenIdle(cts.Token); - - await WaitOneAsync(pool); - - cts.Cancel(); - // Resume the instance; a rapid close-reopen-close may have already replaced the semaphore - pool.Dispose(); - if (ReferenceEquals(Program.Pool, pool)) - Program.Pool = null; - } - - await AppLifecycleHelper.InitializeAppComponentsAsync(); - } - } - - /// - /// Gets invoked when the application is activated. - /// - public async Task OnActivatedAsync(AppActivationArguments activatedEventArgs) - { - var activatedEventArgsData = activatedEventArgs.Data; - - Logger.LogInformation($"The app is being activated. Activation type: {activatedEventArgsData?.GetType().Name ?? "Unknown"}"); - - // InitializeApplication accesses UI, needs to be called on UI thread - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() - => MainWindow.Instance.InitializeApplicationAsync(activatedEventArgsData)); - } - - /// - /// Gets invoked when the main window is activated. - /// - private void Window_Activated(object sender, WindowActivatedEventArgs args) - { - Logger.LogInformation($"Window_Activated: State={args.WindowActivationState}"); - - ActiveSessionTracker.OnActivationChanged(args.WindowActivationState != WindowActivationState.Deactivated); - - if (args.WindowActivationState != WindowActivationState.Deactivated) - AppModel.IsMainWindowClosed = false; - - if (args.WindowActivationState != WindowActivationState.CodeActivated && - args.WindowActivationState != WindowActivationState.PointerActivated) - return; - - ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = -Environment.ProcessId; - - // Reclaim the tray icon if a sibling instance's exit removed the shared-GUID icon - SystemTrayIcon?.EnsureCreated(); - } - - /// - /// Gets invoked when the application execution is closed. - /// - /// - /// Saves the current state of the app such as opened tabs, and disposes all cached resources. - /// - private async void Window_Closed(object sender, WindowEventArgs args) - { - // Let the final close after background teardown proceed - if (_isWindowTeardownCompleted) - return; - - // Stop dispatcher timers before the close handler yields and window teardown begins. - AppModel.IsMainWindowClosed = true; - - // Save application state and stop any background activity - IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService(); - StatusCenterViewModel statusCenterViewModel = Ioc.Default.GetRequiredService(); - ICommandManager commandManager = Ioc.Default.GetRequiredService(); - - // A Workaround for the crash (#10110) - if (_LastOpenedFlyout?.IsOpen ?? false) - { - args.Handled = true; - _LastOpenedFlyout.Closed += (sender, e) => App.Current.Exit(); - _LastOpenedFlyout.Hide(); - return; - } - - // Persist the final active stretch; it is reported on the next launch - ActiveSessionTracker.OnActivationChanged(false); - - // Save the current tab list in case it was overwriten by another instance - if (userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp || userSettingsService.AppSettingsService.RestoreTabsOnStartup) - AppLifecycleHelper.SaveSessionTabs(); - else - await commandManager.CloseAllTabs.ExecuteAsync(); - - if (OutputPath is not null) - { - var instance = MainPageViewModel.AppInstances.FirstOrDefault(x => - (x.TabItemContent ?? throw new InvalidOperationException("A tab does not have content.")).IsCurrentInstance); - if (instance is null) - return; - - var items = (instance.TabItemContent as ShellPanesPage)?.ActivePane?.SlimContentPage?.SelectedItems; - if (items is null) - return; - - var results = items.Select(x => x.ItemPath!).ToList(); - System.IO.File.WriteAllLines(OutputPath, results); - - using var eventHandle = PInvoke.CreateEvent(null, false, false, "FILEDIALOG"); - PInvoke.SetEvent(eventHandle); - } - - // Dev, preview and stable all run as "Files"; only this channel's other instances block parking - static bool IsSameChannelInstance(Process p) - { - if (p.Id == Environment.ProcessId) - return false; - - try - { - return p.MainModule?.FileName.StartsWith(Package.Current.EffectivePath, StringComparison.OrdinalIgnoreCase) ?? false; - } - catch - { - // Access is denied reading another channel's MainModule - return false; - } - } - - // Continue running the app on the background - var isClosedToBackground = false; - if (userSettingsService.GeneralSettingsService.LeaveAppRunning && - !AppModel.ForceProcessTermination && - !Process.GetProcessesByName("Files").Any(IsSameChannelInstance)) - { - // Handled set after an await is read too late to cancel the close - args.Handled = true; - isClosedToBackground = true; - - // Close open content dialogs - UIHelpers.CloseAllDialogs(); - - // Tear down the shell preview host (prevhost.exe) while the dispatcher still pumps; parking must not keep it attached - SafetyExtensions.IgnoreExceptions(() => Ioc.Default.GetRequiredService().UnloadPreview()); - - // Close all notification banners except in progress - statusCenterViewModel.RemoveAllCompletedItems(); - - // Cache the window instead of closing it - MainWindow.Instance.AppWindow.Hide(); - - // Close all tabs - MainPageViewModel.AppInstances.ForEach(tabItem => tabItem.Unload()); - MainPageViewModel.AppInstances.Clear(); - - // Wait for all properties windows to close - await FilePropertiesHelpers.WaitClosingAll(); - - // Claim INSTANCE_ACTIVE before parking; it may still name an already-exited sibling - ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = -Environment.ProcessId; - - // Sleep current instance - var pool = new Semaphore(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance"); - Program.Pool = pool; - - // Displays a notification the first time the app goes to the background - if (userSettingsService.AppSettingsService.ShowBackgroundRunningNotification) - { - SafetyExtensions.IgnoreExceptions(() => - { - AppToastNotificationHelper.ShowBackgroundRunningToast(); - - userSettingsService.AppSettingsService.ShowBackgroundRunningNotification = false; - }); - } - - var cts = new CancellationTokenSource(); - TryEmptyWorkingSetWhenIdle(cts.Token); - - // Waiting must not block the dispatcher; WinRT wrapper finalizers stall until it pumps again - await WaitOneAsync(pool); - - cts.Cancel(); - // Resume the instance; a rapid close-reopen-close may have already replaced the semaphore - pool.Dispose(); - if (ReferenceEquals(Program.Pool, pool)) - Program.Pool = null; - - if (!AppModel.ForceProcessTermination) - { - _ = AppLifecycleHelper.CheckAppUpdate(); - return; - } - } - - // Stop the tray icon's hidden window before continuing teardown so a late "Quit" - // click can't dispatch into OnQuitClicked once Application.Current is null. - SystemTrayIcon?.Dispose(); - SystemTrayIcon = null; - - // Method can take a long time, make sure the window is hidden - await Task.Yield(); - - // Try to maintain clipboard data after app close - SafetyExtensions.IgnoreExceptions(() => - { - var dataPackage = Clipboard.GetContent(); - if (dataPackage.Properties.PackageFamilyName == Package.Current.Id.FamilyName) - { - if (dataPackage.Contains(StandardDataFormats.StorageItems)) - Clipboard.Flush(); - } - }, - Logger); - - // Destroy cached properties windows - FilePropertiesHelpers.DestroyCachedWindows(); - - // Wait for ongoing file operations - FileOperationsHelpers.WaitForCompletion(); - - // Close the still-alive window for real now that teardown is done - if (isClosedToBackground && !_isWindowTeardownCompleted) - { - _isWindowTeardownCompleted = true; - MainWindow.Instance.Close(); - } - } - - private static async Task WaitOneAsync(WaitHandle handle) - { - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var registration = ThreadPool.RegisterWaitForSingleObject( - handle, - static (state, _) => ((TaskCompletionSource)state!).TrySetResult(), - tcs, - Timeout.InfiniteTimeSpan, - executeOnlyOnce: true); - - await tcs.Task; - registration.Unregister(null); - } - - private static void TryEmptyWorkingSetWhenIdle(CancellationToken cancellationToken) - { - static void AggressiveGC(Windows.Win32.Foundation.HANDLE processHandle, CancellationToken cancellationToken) - { - GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; - GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true); - GC.WaitForPendingFinalizers(); - GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, true, true); - Thread.Sleep(1000); - - if (cancellationToken.IsCancellationRequested) - return; - - PInvoke.K32EmptyWorkingSet(processHandle); - } - - new Thread(() => - { - using var process = Process.GetCurrentProcess(); - var processHandle = new Windows.Win32.Foundation.HANDLE(process.Handle); - - // Try to empty the working set - AggressiveGC(processHandle, cancellationToken); - - if (cancellationToken.IsCancellationRequested) - return; - - FileOperationsHelpers.WaitForCompletion(); - if (cancellationToken.IsCancellationRequested) - return; - - // After all pending file operations are completed, try to empty the working set again - AggressiveGC(processHandle, cancellationToken); - }) - { IsBackground = true }.Start(); - } -#endif /// /// Gets invoked when the last opened flyout is closed. diff --git a/src/Files.App/Constants.cs b/src/Files.App/Constants.cs index 0c1d9e5612da..2b7dd68f1cae 100644 --- a/src/Files.App/Constants.cs +++ b/src/Files.App/Constants.cs @@ -208,13 +208,6 @@ public static class DragAndDrop public static class UserEnvironmentPaths { -#if WINDOWS - public static readonly string DesktopPath = Windows.Storage.UserDataPaths.GetDefault().Desktop; - - public static readonly string DownloadsPath = Windows.Storage.UserDataPaths.GetDefault().Downloads; - - public static readonly string LocalAppDataPath = Windows.Storage.UserDataPaths.GetDefault().LocalAppData; -#else private static readonly Files.Platform.Linux.LinuxUserDirectories _userDirectories = new(); public static readonly string DesktopPath = _userDirectories.Desktop; @@ -225,33 +218,20 @@ public static class UserEnvironmentPaths public static readonly string LocalAppDataPath = Environment.GetEnvironmentVariable("XDG_DATA_HOME") is { Length: > 0 } dataHome && System.IO.Path.IsPathRooted(dataHome) ? dataHome : System.IO.Path.Combine(_userDirectories.Home, ".local", "share"); -#endif // Currently is the command to open the folder from cmd ("cmd /c start Shell:RecycleBinFolder") -#if WINDOWS - public const string RecycleBinPath = @"Shell:RecycleBinFolder"; -#else // Virtual location of the freedesktop.org trash; listed through ITrashService public const string RecycleBinPath = @"trash:///"; -#endif public const string NetworkFolderPath = @"Shell:NetworkPlacesFolder"; public const string MyComputerPath = @"Shell:MyComputerFolder"; -#if WINDOWS - public static readonly string TempPath = Environment.GetEnvironmentVariable("TEMP") ?? ""; -#else public static readonly string TempPath = System.IO.Path.GetTempPath(); -#endif public static readonly string HomePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); -#if WINDOWS - public static readonly string SystemRootPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows); -#else public static readonly string SystemRootPath = "/"; -#endif public static readonly string RecentItemsPath = Environment.GetFolderPath(Environment.SpecialFolder.Recent); @@ -260,11 +240,7 @@ public static class UserEnvironmentPaths static UserEnvironmentPaths() { var systemDrive = Environment.GetEnvironmentVariable("SystemDrive"); -#if WINDOWS - SystemDrivePath = !string.IsNullOrEmpty(systemDrive) ? systemDrive : "C:"; -#else SystemDrivePath = "/"; -#endif } public static Dictionary ShellPlaces = diff --git a/src/Files.App/Data/Commands/HotKey/HotKey.cs b/src/Files.App/Data/Commands/HotKey/HotKey.cs index 98efbd8ac580..aa4a3f7a8f7b 100644 --- a/src/Files.App/Data/Commands/HotKey/HotKey.cs +++ b/src/Files.App/Data/Commands/HotKey/HotKey.cs @@ -3,10 +3,6 @@ using System.Collections.Frozen; using System.Text; -#if WINDOWS -using Windows.Win32; -using Windows.Win32.UI.Input.KeyboardAndMouse; -#endif namespace Files.App.Data.Commands { @@ -375,7 +371,6 @@ private static string GetLocalizedNumPadKey(string key) private static string GetKeyCharacter(Keys key) { -#if !WINDOWS // LINUX-TODO(keyboard): US-layout approximation of MapVirtualKey(VK_TO_CHAR); query XKB for the active layout instead var vk = (uint)key; return vk switch @@ -394,14 +389,6 @@ private static string GetKeyCharacter(Keys key) 0xDE => "'", _ => string.Empty }; -#else - char result = (char)PInvoke.MapVirtualKey((uint)key, MAP_VIRTUAL_KEY_TYPE.MAPVK_VK_TO_CHAR); - - if (result > 0) - return result.ToString(); - - return string.Empty; -#endif } } } diff --git a/src/Files.App/Data/Commands/HotKey/HotKeyHelpers.cs b/src/Files.App/Data/Commands/HotKey/HotKeyHelpers.cs index 60727482f816..7bc65ba54d7f 100644 --- a/src/Files.App/Data/Commands/HotKey/HotKeyHelpers.cs +++ b/src/Files.App/Data/Commands/HotKey/HotKeyHelpers.cs @@ -13,12 +13,7 @@ internal static partial class HotKeyHelpers public static Keys GetHotKeyKey(KeyRoutedEventArgs e) => (Keys)GetHotKeyVirtualKey(e); -#if WINDOWS - public static VirtualKey GetHotKeyVirtualKey(KeyRoutedEventArgs e) - => e.Key; -#else public static partial VirtualKey GetHotKeyVirtualKey(KeyRoutedEventArgs e); -#endif public static KeyModifiers GetCurrentKeyModifiers() { diff --git a/src/Files.App/Data/Contexts/HomePage/HomePageContext.cs b/src/Files.App/Data/Contexts/HomePage/HomePageContext.cs index 9cab4f66bb4c..20145cb3bbec 100644 --- a/src/Files.App/Data/Contexts/HomePage/HomePageContext.cs +++ b/src/Files.App/Data/Contexts/HomePage/HomePageContext.cs @@ -16,15 +16,11 @@ public sealed partial class HomePageContext : ObservableObject, IHomePageContext private static IHomeFolder CreateHomeFolder() { -#if WINDOWS - return new HomeFolder(); -#else return new LinuxHomeFolder( Ioc.Default.GetRequiredService(), Ioc.Default.GetRequiredService(), Ioc.Default.GetRequiredService(), Ioc.Default.GetRequiredService()); -#endif } private WidgetCardItem? rightClickedItem = null; diff --git a/src/Files.App/Data/Contracts/IStorageArchiveService.cs b/src/Files.App/Data/Contracts/IStorageArchiveService.cs index bd4a761ffa12..693922d0bd8a 100644 --- a/src/Files.App/Data/Contracts/IStorageArchiveService.cs +++ b/src/Files.App/Data/Contracts/IStorageArchiveService.cs @@ -1,9 +1,6 @@ // Copyright (c) Files Community // SPDX-License-Identifier: MPL-2.0 -#if WINDOWS -using SevenZip; -#endif using System.Text; namespace Files.App.Data.Contracts @@ -92,14 +89,5 @@ public interface IStorageArchiveService /// Null if the archive file doesn't need to detect encoding or its encoding can't be detected; otherwise, the encoding detected. Task DetectEncodingAsync(string archiveFilePath); -#if WINDOWS - /// - /// Gets the instance from the archive file path. - /// - /// The archive file path to generate an instance. - /// The password to decrypt the archive file if applicable. - /// An instance of if the specified item is archive; otherwise null. - Task GetSevenZipExtractorAsync(string archiveFilePath, string password = ""); -#endif } } diff --git a/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.Linux.cs b/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.Linux.cs index ed9d5f252d8a..9a99b13d307b 100644 --- a/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.Linux.cs +++ b/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions; using Files.Platform.Abstractions.Launching; using Files.Platform.Abstractions.Mime; @@ -166,4 +165,3 @@ private static async Task CreateFromTemplateAsync(NewItemTemplate template) } } } -#endif diff --git a/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.cs b/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.cs index 7715ceb81b8a..703e8746a110 100644 --- a/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.cs +++ b/src/Files.App/Data/Factories/ContentPageContextFlyoutFactory.cs @@ -33,11 +33,7 @@ public static List GetItemContextCommandsWithout public static Task> GetItemContextShellCommandsAsync(string? workingDir, List selectedItems, bool shiftPressed, bool showOpenMenu, CancellationToken cancellationToken) { -#if !WINDOWS return GetLinuxItemContextCommandsAsync(workingDir, selectedItems, shiftPressed, showOpenMenu, cancellationToken); -#else - return ShellContextFlyoutFactory.GetShellContextmenuAsync(shiftPressed: shiftPressed, showOpenMenu: showOpenMenu, workingDirectory: workingDir, selectedItems: selectedItems, cancellationToken: cancellationToken); -#endif } public static List Filter(List items, List selectedItems, bool shiftPressed, CurrentInstanceViewModel currentInstanceViewModel, bool removeOverflowMenu = true) @@ -374,11 +370,7 @@ private static List BuildBaseItemMenuItems(Conte ThemedIconStyle = state.Commands[Commands.AddItem].Glyph.ThemedIconStyle }, Text = state.Commands[Commands.AddItem].Label, - #if WINDOWS - Items = GetNewItemItems(state.CommandsViewModel, state.CanCreateFileInPage), -#else Items = GetLinuxNewItemItems(state.CanCreateFileInPage, state.Commands[Commands.CreateFolder], cancellationToken), -#endif ShowItem = !state.ItemsSelected, ShowInFtpPage = true }, @@ -747,11 +739,7 @@ private static ContextMenuBuildState CaptureMenuState(BaseLayoutViewModel comman i => (i.PrimaryItemAttribute == StorageItemTypes.File && !i.IsShortcut && !i.IsExecutable) || (i.PrimaryItemAttribute == StorageItemTypes.Folder && i.IsArchive)); bool areAllItemsFolders = selectedItems.All(i => i.PrimaryItemAttribute == StorageItemTypes.Folder); -#if !WINDOWS bool isLinux = true; -#else - bool isLinux = false; -#endif bool isDriveRoot = !isLinux && itemViewModel?.CurrentFolder is not null && (itemViewModel.CurrentFolder.ItemPath == Path.GetPathRoot(itemViewModel.CurrentFolder.ItemPath)); bool compatibleWallpaper = selectedItemsPropertiesViewModel?.IsCompatibleToSetAsWindowsWallpaper ?? false; @@ -890,63 +878,7 @@ private static ContextMenuBuildState CaptureMenuState(BaseLayoutViewModel comman public static List GetNewItemItems(BaseLayoutViewModel commandsViewModel, bool canCreateFileInPage) { -#if !WINDOWS return GetLinuxNewItemItems(canCreateFileInPage); -#else - var list = new List() - { - new ContextMenuFlyoutItemViewModelBuilder(Commands.CreateFolder).Build(), - new ContextMenuFlyoutItemViewModel() - { - Text = Strings.File.GetLocalizedResource(), - Glyph = "\uE7C3", - Command = commandsViewModel.CreateNewFileCommand, - ShowInFtpPage = true, - ShowInZipPage = true, - IsEnabled = canCreateFileInPage - }, - new ContextMenuFlyoutItemViewModelBuilder(Commands.CreateShortcutFromDialog).Build(), - new ContextMenuFlyoutItemViewModel() - { - ItemType = ContextMenuFlyoutItemType.Separator, - } - }; - - if (canCreateFileInPage) - { - var cachedNewContextMenuEntries = AddItemService.GetEntries(); - cachedNewContextMenuEntries?.ForEach(i => - { - if (!string.IsNullOrEmpty(i.IconBase64)) - { - // loading the bitmaps takes a while, so this caches them - byte[] bitmapData = Convert.FromBase64String(i.IconBase64); - using var ms = new MemoryStream(bitmapData); - var bitmap = new BitmapImage(); - _ = bitmap.SetSourceAsync(ms.AsRandomAccessStream()); - list.Add(new ContextMenuFlyoutItemViewModel() - { - Text = i.Name, - BitmapIcon = bitmap, - Command = commandsViewModel.CreateNewFileCommand, - CommandParameter = i, - }); - } - else - { - list.Add(new ContextMenuFlyoutItemViewModel() - { - Text = i.Name, - Glyph = "\xE7C3", - Command = commandsViewModel.CreateNewFileCommand, - CommandParameter = i, - }); - } - }); - } - - return list; -#endif } } } diff --git a/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs b/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs index f02e4f4290fa..0e178b806e70 100644 --- a/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs +++ b/src/Files.App/Data/Factories/ShellContextFlyoutFactory.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.App.Dialogs; using Files.Platform.Abstractions.Launching; using Files.Platform.Abstractions.Mime; @@ -78,4 +77,3 @@ private static async Task LoadOpenWithItemsAsync(ContextMenuFlyoutItemViewModel } } } -#endif diff --git a/src/Files.App/Data/Factories/ShellContextFlyoutHelper.Windows.cs b/src/Files.App/Data/Factories/ShellContextFlyoutHelper.Windows.cs deleted file mode 100644 index e369c7a4fa2e..000000000000 --- a/src/Files.App/Data/Factories/ShellContextFlyoutHelper.Windows.cs +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using CommunityToolkit.WinUI; -using Files.App.Helpers.ContextFlyouts; -using Files.Shared.Helpers; -using Microsoft.UI.Input; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Media.Imaging; -using System.IO; -using System.Text; -using Windows.System; -using Windows.UI.Core; -using Windows.Win32; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Helpers -{ - public static partial class ShellContextFlyoutFactory - { - private static (string Label, string AccessKey) ExtractLabelAndAccessKey(string rawLabel) - { - if (string.IsNullOrEmpty(rawLabel)) - return (string.Empty, string.Empty); - - string accessKey = string.Empty; - var labelBuilder = new StringBuilder(rawLabel.Length); - - for (int i = 0; i < rawLabel.Length; i++) - { - char current = rawLabel[i]; - if (current != '&') - { - labelBuilder.Append(current); - continue; - } - - if (i + 1 >= rawLabel.Length) - { - labelBuilder.Append('&'); - continue; - } - - char next = rawLabel[++i]; - if (next == '&') - { - labelBuilder.Append('&'); - continue; - } - - if (string.IsNullOrEmpty(accessKey) && !char.IsWhiteSpace(next)) - accessKey = char.ToUpperInvariant(next).ToString(); - - labelBuilder.Append(next); - } - - return (labelBuilder.ToString(), accessKey); - } - - private static ContextMenuFlyoutItemViewModel CreateShellMenuItem(Win32ContextMenuItem menuFlyoutItem, BitmapImage? image) - { - var (label, accessKey) = ExtractLabelAndAccessKey(menuFlyoutItem.Label ?? string.Empty); - return new ContextMenuFlyoutItemViewModel - { - Text = label, - AccessKey = accessKey, - Tag = menuFlyoutItem, - BitmapIcon = image, - }; - } - - private static async Task LoadMenuFlyoutItemAsync( - List menuItemsListLocal, - ContextMenu contextMenu, - IEnumerable menuFlyoutItems, - CancellationToken cancellationToken, - bool showIcons = true, - int itemsBeforeOverflow = int.MaxValue) - { - if (cancellationToken.IsCancellationRequested) - return; - - var itemsCount = 0; // Separators do not count for reaching the overflow threshold - var menuItems = menuFlyoutItems.TakeWhile(x => x.Type == MENU_ITEM_TYPE.MFT_SEPARATOR || ++itemsCount <= itemsBeforeOverflow).ToList(); - var overflowItems = menuFlyoutItems.Except(menuItems).ToList(); - - if (overflowItems.Any(x => x.Type != MENU_ITEM_TYPE.MFT_SEPARATOR)) - { - var moreItem = menuItemsListLocal.FirstOrDefault(x => x.ID == "ItemOverflow"); - if (moreItem is null) - { - var menuLayoutSubItem = new ContextMenuFlyoutItemViewModel() - { - Text = Strings.ShowMoreOptions.GetLocalizedResource(), - Glyph = "\xE712", - }; - await LoadMenuFlyoutItemAsync(menuLayoutSubItem.Items - ?? throw new InvalidOperationException("The shell overflow menu has not been initialized."), contextMenu, overflowItems, cancellationToken, showIcons); - menuItemsListLocal.Insert(0, menuLayoutSubItem); - } - else - { - await LoadMenuFlyoutItemAsync(moreItem.Items - ?? throw new InvalidOperationException("The shell overflow menu has not been initialized."), contextMenu, overflowItems, cancellationToken, showIcons); - } - } - - foreach (var menuFlyoutItem in menuItems - .SkipWhile(x => x.Type == MENU_ITEM_TYPE.MFT_SEPARATOR) // Remove leading separators - .Reverse() - .SkipWhile(x => x.Type == MENU_ITEM_TYPE.MFT_SEPARATOR)) // Remove trailing separators - { - if (cancellationToken.IsCancellationRequested) - break; - - // Avoid duplicate separators - if ((menuFlyoutItem.Type == MENU_ITEM_TYPE.MFT_SEPARATOR) && (menuItemsListLocal.FirstOrDefault()?.ItemType == ContextMenuFlyoutItemType.Separator)) - continue; - - BitmapImage? image = null; - if (showIcons && menuFlyoutItem.Icon is { Length: > 0 }) - { - image = new BitmapImage(); - using var ms = new MemoryStream(menuFlyoutItem.Icon); - await image.SetSourceAsync(ms.AsRandomAccessStream()); - } - - if (menuFlyoutItem.Type is MENU_ITEM_TYPE.MFT_SEPARATOR) - { - var menuLayoutItem = new ContextMenuFlyoutItemViewModel() - { - ItemType = ContextMenuFlyoutItemType.Separator, - Tag = menuFlyoutItem - }; - menuItemsListLocal.Insert(0, menuLayoutItem); - } - else if (!string.IsNullOrEmpty(menuFlyoutItem.Label) && menuFlyoutItem.SubItems is not null) - { - if (string.Equals(menuFlyoutItem.Label, Win32Helper.ExtractStringFromDLL("shell32.dll", 30312))) - menuFlyoutItem.CommandString = "sendto"; - - var menuLayoutSubItem = CreateShellMenuItem(menuFlyoutItem, image); - menuLayoutSubItem.Items = []; - - if (menuFlyoutItem.SubItems.Any()) - { - await LoadMenuFlyoutItemAsync(menuLayoutSubItem.Items, contextMenu, menuFlyoutItem.SubItems, cancellationToken, showIcons); - } - else - { - menuLayoutSubItem.LoadSubMenuAction = async () => - { - if (await contextMenu.LoadSubMenu(menuFlyoutItem.SubItems)) - await LoadMenuFlyoutItemAsync(menuLayoutSubItem.Items, contextMenu, menuFlyoutItem.SubItems, cancellationToken, showIcons); - }; - } - - menuItemsListLocal.Insert(0, menuLayoutSubItem); - } - else if (!string.IsNullOrEmpty(menuFlyoutItem.Label)) - { - var menuLayoutItem = CreateShellMenuItem(menuFlyoutItem, image); - menuLayoutItem.Command = new AsyncRelayCommand(x => InvokeShellMenuItemAsync(contextMenu, x)); - menuLayoutItem.CommandParameter = menuFlyoutItem; - menuItemsListLocal.Insert(0, menuLayoutItem); - } - } - - async Task InvokeShellMenuItemAsync(ContextMenu contextMenu, object? tag) - { - if (tag is not Win32ContextMenuItem menuItem) - return; - - var menuId = menuItem.ID; - var isFont = FileExtensionHelpers.IsFontFile(contextMenu.ItemsPath[0]); - var verb = menuItem.CommandString; - switch (verb) - { - case "install" when isFont: - await Win32Helper.InstallFontsAsync([.. contextMenu.ItemsPath], false); - break; - - case "installAllUsers" when isFont: - await Win32Helper.InstallFontsAsync([.. contextMenu.ItemsPath], true); - break; - - case "mount": - var vhdPath = contextMenu.ItemsPath[0]; - await Win32Helper.MountVhdDisk(vhdPath); - break; - - case "format": - var drivePath = contextMenu.ItemsPath[0]; - await Win32Helper.OpenFormatDriveDialog(drivePath); - break; - - case "Windows.PowerShell.Run": - await contextMenu.InvokeItem( - menuId, - contextMenu.ItemsPath[0].EndsWith(".ps1") ? Path.GetDirectoryName(contextMenu.ItemsPath[0]) : null - ); - break; - - default: - await contextMenu.InvokeItem(menuId); - break; - } - - //contextMenu.Dispose(); // Prevents some menu items from working (TBC) - } - } - - private static async Task> GetWindowsContextMenuAsync(bool showOpenMenu, bool shiftPressed, string? workingDirectory, List? selectedItems, CancellationToken cancellationToken) - { - var menuItemsList = new List(); - var filePaths = selectedItems is { Count: > 0 } - ? selectedItems.Select(x => x.ItemPath!).ToArray() - : [workingDirectory ?? throw new ArgumentException("A working directory is required when no items are selected.", nameof(workingDirectory))]; - - Func FilterMenuItems(bool showOpenMenu) - { - var knownItems = new HashSet() - { - "opennew", "opencontaining", "opennewprocess", - "runas", "runasuser", "pintohome", "PinToStartScreen", - "cut", "copy", "paste", "delete", "properties", "link", - "Windows.ModernShare", "setdesktopwallpaper", - "eject", "rename", "explore", "openinfiles", "extract", - "copyaspath", "undelete", "empty", "format", "rotate90", "rotate270", - Win32Helper.ExtractStringFromDLL("shell32.dll", 34593), // Add to collection - Win32Helper.ExtractStringFromDLL("shell32.dll", 5384), // Pin to Start - Win32Helper.ExtractStringFromDLL("shell32.dll", 5385), // Unpin from Start - Win32Helper.ExtractStringFromDLL("shell32.dll", 5386), // Pin to taskbar - Win32Helper.ExtractStringFromDLL("shell32.dll", 5387), // Unpin from taskbar - "{9F156763-7844-4DC4-B2B1-901F640F5155}", // Open in Terminal - }; - - bool filterMenuItemsImpl(string? menuItem) => !string.IsNullOrEmpty(menuItem) - && (knownItems.Contains(menuItem) || (!showOpenMenu && menuItem.Equals("open", StringComparison.OrdinalIgnoreCase))); - - return filterMenuItemsImpl; - } - - var contextMenu = await ContextMenu.GetContextMenuForFiles(filePaths, - shiftPressed ? PInvoke.CMF_EXTENDEDVERBS : PInvoke.CMF_NORMAL, FilterMenuItems(showOpenMenu)); - - if (contextMenu is not null) - await LoadMenuFlyoutItemAsync(menuItemsList, contextMenu, contextMenu.Items!, cancellationToken, true); - - if (cancellationToken.IsCancellationRequested) - menuItemsList.Clear(); - - return menuItemsList; - } - } -} diff --git a/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs b/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs index 6d377a728987..19e2c91743b6 100644 --- a/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs +++ b/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs @@ -23,12 +23,8 @@ public static partial class ShellContextFlyoutFactory public static async Task> GetShellContextmenuAsync(bool showOpenMenu, bool shiftPressed, string? workingDirectory, List? selectedItems, CancellationToken cancellationToken) { -#if !WINDOWS // No shell extensions on Linux: skip the Win32 shell menu entirely (no COM, no delay) return await GetLinuxContextMenuAsync(selectedItems, cancellationToken); -#else - return await GetWindowsContextMenuAsync(showOpenMenu, shiftPressed, workingDirectory, selectedItems, cancellationToken); -#endif } diff --git a/src/Files.App/Data/Items/AccessControlPrincipal.Windows.cs b/src/Files.App/Data/Items/AccessControlPrincipal.Windows.cs deleted file mode 100644 index 5de474bce0ea..000000000000 --- a/src/Files.App/Data/Items/AccessControlPrincipal.Windows.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Security; - -namespace Files.App.Data.Items -{ - public sealed partial class AccessControlPrincipal - { - partial void ResolveAccount(string sid) - { - ResolveAccountCore(sid); - } - - private unsafe void ResolveAccountCore(string sid) - { - if (!PInvoke.ConvertStringSidToSid(sid, out var lpSid)) - return; - - try - { - char[] lpName = []; - char[] lpDomain = []; - uint cchName = 0, cchDomainName = 0; - - // Get size of account name and domain name - _ = PInvoke.LookupAccountSid(string.Empty, lpSid, lpName, ref cchName, lpDomain, ref cchDomainName, out _); - - // Ensure requested capacity - lpName = new char[cchName]; - lpDomain = new char[cchDomainName]; - - // Get account name and domain - bool bResult = PInvoke.LookupAccountSid(string.Empty, lpSid, lpName, ref cchName, lpDomain, ref cchDomainName, out var snu); - if (!bResult) - return; - - PrincipalType = snu switch - { - // Group - var x when - (x == SID_NAME_USE.SidTypeAlias || - x == SID_NAME_USE.SidTypeGroup || - x == SID_NAME_USE.SidTypeWellKnownGroup) - => AccessControlPrincipalType.Group, - - // User - SID_NAME_USE.SidTypeUser - => AccessControlPrincipalType.User, - - // Unknown - _ => AccessControlPrincipalType.Unknown - }; - - // Replace domain name with computer name if the account type is user or alias type - if (snu == SID_NAME_USE.SidTypeUser || snu == SID_NAME_USE.SidTypeAlias) - { - uint size = 256; - lpDomain = new char[size]; - bResult = PInvoke.GetComputerName(lpDomain, ref size); - if (!bResult) - return; - } - - Name = lpName.AsSpan().ToString(); - Domain = lpDomain.AsSpan().ToString().ToLower(); - - IsValid = true; - } - finally - { - Marshal.FreeHGlobal((nint)lpSid.Value); - } - } - } -} diff --git a/src/Files.App/Data/Items/ContextMenu.cs b/src/Files.App/Data/Items/ContextMenu.cs index 399e6632e5bc..1735d74a99ce 100644 --- a/src/Files.App/Data/Items/ContextMenu.cs +++ b/src/Files.App/Data/Items/ContextMenu.cs @@ -1,9 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if WINDOWS || FILES_WIN32_COMPAT -using Windows.Win32.UI.WindowsAndMessaging; -#endif namespace Files.App.Data.Items { @@ -33,9 +30,6 @@ public class Win32ContextMenuItem public int ID { get; set; } // Valid only in current menu to invoke item public string? Label { get; set; } public string? CommandString { get; set; } -#if WINDOWS || FILES_WIN32_COMPAT - public MENU_ITEM_TYPE Type { get; set; } -#endif public List? SubItems { get; set; } } } diff --git a/src/Files.App/Data/Items/DriveItem.cs b/src/Files.App/Data/Items/DriveItem.cs index ca60df0b5d9b..30c5fcabf67c 100644 --- a/src/Files.App/Data/Items/DriveItem.cs +++ b/src/Files.App/Data/Items/DriveItem.cs @@ -165,10 +165,6 @@ public float PercentageUsed if (!SetProperty(ref percentageUsed, value)) return; -#if WINDOWS - if (Type == DriveType.Fixed) - ShowStorageSense = percentageUsed >= Constants.Widgets.Drives.LowStorageSpacePercentageThreshold; -#endif } } @@ -182,9 +178,7 @@ public bool ShowStorageSense public string Id => Path ?? throw new InvalidOperationException("The drive path has not been initialized."); public string Name => Root?.DisplayName -#if !WINDOWS ?? Text // volumes that are not mounted yet have no root folder -#endif ?? throw new InvalidOperationException("The drive root has not been initialized."); public object? Children => IsExpandableFolder ? (childItems ??= []) : null; @@ -260,18 +254,10 @@ public static async Task CreateFromPropertiesAsync(StorageFolder root if (imageStream is not null) item.IconData = await imageStream.ToByteArrayAsync(); -#if WINDOWS - item.Text = type switch - { - DriveType.CDRom when !string.IsNullOrEmpty(label) => root.DisplayName.Replace(label.Left(32), label), - _ => root.DisplayName - }; -#else // The label already is the display name (volume label, " Volume" or "File System") item.Text = !string.IsNullOrWhiteSpace(label) ? label : root.DisplayName; if (string.IsNullOrWhiteSpace(item.Text) && root.Path is "/") item.Text = Strings.LinuxFileSystemRoot.GetLocalizedResource(); -#endif item.Type = type; item.MenuOptions = new ContextMenuOptions { @@ -292,11 +278,9 @@ public static async Task CreateFromPropertiesAsync(StorageFolder root public async Task UpdatePropertiesAsync() { -#if !WINDOWS // Not mounted: there is nothing to measure, the size is known from UDisks2 if (DriveHelpers.IsUnmountedPath(Path)) return; -#endif try { @@ -326,7 +310,6 @@ public async Task UpdatePropertiesAsync() catch { } } -#if !WINDOWS var info = await Task.Run(() => { if (Files.Platform.Linux.Volumes.HeadlessDriveFixture.Find(Path) is { } synthetic) @@ -346,7 +329,6 @@ public async Task UpdatePropertiesAsync() OnPropertyChanged(nameof(ShowDriveDetails)); return; -#endif var root = Root ?? throw new InvalidOperationException("The drive root has not been initialized."); var properties = await root.Properties.RetrievePropertiesAsync((string[])["System.FreeSpace", "System.Capacity", "System.Volume.FileSystem"]) .AsTask().WithTimeoutAsync(TimeSpan.FromSeconds(5)); @@ -404,9 +386,7 @@ public int CompareTo(INavigationControlItem? other) public async Task LoadThumbnailAsync() { -#if !WINDOWS IconData ??= await DriveHelpers.GetDriveIconAsync(Type, Constants.ShellIconSizes.Small); -#endif if (IconData is null && !string.IsNullOrEmpty(DeviceID) && !string.Equals(DeviceID, "network-folder")) { var result = await FileThumbnailHelper.GetIconAsync( diff --git a/src/Files.App/Data/Items/IListedItem.cs b/src/Files.App/Data/Items/IListedItem.cs index 5cd90b468ac7..3b6e010a9a55 100644 --- a/src/Files.App/Data/Items/IListedItem.cs +++ b/src/Files.App/Data/Items/IListedItem.cs @@ -53,11 +53,7 @@ public interface IListedItem DateTimeOffset ItemDateCreatedReal { get; set; } string? ItemDateModified { get; } DateTimeOffset ItemDateModifiedReal { get; set; } -#if WINDOWS - BaseStorageFile? ItemFile { get; set; } -#else IFile? ItemFile { get; set; } -#endif string? ItemNameRaw { get; set; } string? ItemPath { get; set; } ObservableCollection? ItemProperties { get; set; } diff --git a/src/Files.App/Data/Items/ListedItem.FileTags.cs b/src/Files.App/Data/Items/ListedItem.FileTags.cs index a25e9836004a..8b77a2aa8409 100644 --- a/src/Files.App/Data/Items/ListedItem.FileTags.cs +++ b/src/Files.App/Data/Items/ListedItem.FileTags.cs @@ -22,17 +22,11 @@ public string[]? FileTags get => fileTags; set { -#if !WINDOWS if (fileTags is not null && fileTags.SequenceEqual(value, StringComparer.Ordinal)) return; -#endif // fileTags is null when the item is first created -#if WINDOWS - var fileTagsInitialized = fileTags is not null; -#else // Tags are loaded lazily, so an item that was never loaded counts as untagged and its first edit must still be saved const bool fileTagsInitialized = true; -#endif if (SetProperty(ref fileTags, value)) { Interlocked.Increment(ref fileTagsRevision); @@ -40,10 +34,6 @@ public string[]? FileTags if (fileTagsInitialized) { var path = this.GetRequiredPath(); -#if WINDOWS - var dbInstance = FileTagsHelper.GetDbInstance(); - dbInstance.SetTags(path, FileFRN, value); -#endif _ = FileTagsHelper.WriteFileTagAsync(path, value); } @@ -61,9 +51,6 @@ public void SetLoadedFileTags(string[] tags, long? expectedRevision = null) if (expectedRevision is not null && expectedRevision != FileTagsRevision) return; -#if WINDOWS - FileTags = tags; -#else // A deferred snapshot may predate an edit made through another item for this path. if (FileTagsHelper.TryReadDatabaseFallback(this.GetRequiredPath(), out var fallbackTags)) tags = fallbackTags; @@ -76,7 +63,6 @@ public void SetLoadedFileTags(string[] tags, long? expectedRevision = null) HasTags = tags.Length > 0; OnPropertyChanged(nameof(FileTagsUI)); } -#endif } /// @@ -84,17 +70,10 @@ public void SetLoadedFileTags(string[] tags, long? expectedRevision = null) /// public async Task EditFileTagsAsync(Func edit) { -#if WINDOWS - if (fileTags is null) - SetLoadedFileTags(FileTagsHelper.ReadFileTag(this.GetRequiredPath())); - FileTags = edit(fileTags ?? []); - await Task.CompletedTask; -#else var revision = Interlocked.Increment(ref fileTagsRevision); var tags = await FileTagsHelper.EditFileTagsAsync(this.GetRequiredPath(), edit); if (tags is not null) SetLoadedFileTags(tags, revision); -#endif } } } diff --git a/src/Files.App/Data/Items/ListedItem.Windows.cs b/src/Files.App/Data/Items/ListedItem.Windows.cs deleted file mode 100644 index 431125a7d774..000000000000 --- a/src/Files.App/Data/Items/ListedItem.Windows.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using Windows.Storage; - -namespace Files.App.Utils -{ - public sealed partial class FtpItem - { - public async Task ToStorageItem() - { - var path = this.GetRequiredPath(); - var name = ItemNameRaw ?? throw new InvalidOperationException("The FTP item does not have a name."); - - return PrimaryItemAttribute switch - { - StorageItemTypes.File => await new Utils.Storage.FtpStorageFile(path, name, ItemDateCreatedReal).ToStorageFileAsync(), - StorageItemTypes.Folder => new Utils.Storage.FtpStorageFolder(path, name, ItemDateCreatedReal), - _ => throw new InvalidDataException("The FTP item has an unsupported storage type."), - }; - } - } -} diff --git a/src/Files.App/Data/Items/ListedItem.cs b/src/Files.App/Data/Items/ListedItem.cs index e8b527926330..42cfaafa9670 100644 --- a/src/Files.App/Data/Items/ListedItem.cs +++ b/src/Files.App/Data/Items/ListedItem.cs @@ -468,13 +468,8 @@ public override string ToString() public bool IsDriveRoot => ItemPath == PathNormalization.GetPathRoot(ItemPath); public bool IsElevationRequired { get; set; } -#if WINDOWS - private BaseStorageFile? itemFile; - public BaseStorageFile? ItemFile -#else private IFile? itemFile; public IFile? ItemFile -#endif { get => itemFile; set => SetProperty(ref itemFile, value); diff --git a/src/Files.App/Data/Items/LocationItem.cs b/src/Files.App/Data/Items/LocationItem.cs index 8877ddbb4224..b6d898e0c522 100644 --- a/src/Files.App/Data/Items/LocationItem.cs +++ b/src/Files.App/Data/Items/LocationItem.cs @@ -313,16 +313,11 @@ public override object ToolTip public RecycleBinLocationItem() { -#if WINDOWS - StorageTrashBinService.Watcher.ItemAdded += RefreshSpaceUsed; - StorageTrashBinService.Watcher.ItemDeleted += RefreshSpaceUsed; -#else var trashWatcher = Ioc.Default.GetRequiredService().Watcher; trashWatcher.ItemAdded += RefreshSpaceUsed; trashWatcher.ItemDeleted += RefreshSpaceUsed; trashWatcher.RefreshRequested += RefreshSpaceUsed; trashWatcher.StartWatcher(); -#endif _ = RefreshSpaceUsedAsync(); } diff --git a/src/Files.App/Data/Items/ShellLibraryItem.cs b/src/Files.App/Data/Items/ShellLibraryItem.cs index b0c5c4983bca..68fde3523cd6 100644 --- a/src/Files.App/Data/Items/ShellLibraryItem.cs +++ b/src/Files.App/Data/Items/ShellLibraryItem.cs @@ -7,12 +7,8 @@ public sealed class ShellLibraryItem { public const string EXTENSION = ".library-ms"; -#if WINDOWS - public static readonly string LibrariesPath = Win32Helper.GetFolderFromKnownFolderGUID(new Guid("1B3EA5DC-B587-4786-B4EF-BD1DC332AEAE")); -#else // LINUX-TODO(libraries): Windows libraries (.library-ms) have no Linux equivalent public static readonly string LibrariesPath = string.Empty; -#endif /// /// Full path of library file.
diff --git a/src/Files.App/Data/Items/WidgetDriveCardItem.cs b/src/Files.App/Data/Items/WidgetDriveCardItem.cs index b7f8f3b30a4b..71af6d2ac1e0 100644 --- a/src/Files.App/Data/Items/WidgetDriveCardItem.cs +++ b/src/Files.App/Data/Items/WidgetDriveCardItem.cs @@ -24,23 +24,9 @@ public WidgetDriveCardItem(DriveItem item) public async Task LoadCardThumbnailAsync() { -#if !WINDOWS var result = await DriveHelpers.GetDriveIconAsync(Item.Type, Constants.ShellIconSizes.Large); if (result is null) return; -#else - var result = await FileThumbnailHelper.GetIconAsync( - Item.Path, - Constants.ShellIconSizes.Large, - true, - IconOptions.ReturnIconOnly); - - if (result is null) - { - using var thumbnail = await DriveHelpers.GetThumbnailAsync(Item.Root!); - result ??= await thumbnail.ToByteArrayAsync(); - } -#endif var bitmapImage = await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => result.ToBitmapAsync(), Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal); if (bitmapImage is not null) diff --git a/src/Files.App/Data/Items/WidgetFolderCardItem.Windows.cs b/src/Files.App/Data/Items/WidgetFolderCardItem.Windows.cs deleted file mode 100644 index cf8570edac79..000000000000 --- a/src/Files.App/Data/Items/WidgetFolderCardItem.Windows.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.UI.Xaml.Media.Imaging; -using Windows.Win32; -using Windows.Win32.System.Com; -using Windows.Win32.System.WinRT; -using Windows.Win32.UI.Shell; - -namespace Files.App.Data.Items -{ - public sealed partial class WidgetFolderCardItem - { - public async Task LoadCardThumbnailAsync() - { - if (_isDisposed || string.IsNullOrEmpty(Path)) - return; - - if (Item is null) - { - byte[]? icon = Path == Constants.UserEnvironmentPaths.RecycleBinPath - ? await DriveHelpers.GetDriveIconAsync(null, Constants.ShellIconSizes.Large) - : await FileThumbnailHelper.GetIconAsync(Path, (uint)Constants.ShellIconSizes.Large, true, IconOptions.ReturnIconOnly); - if (icon is not null) - Thumbnail = await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => icon.ToBitmapAsync(), Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal); - return; - } - - var thumbnailSize = (int)(Constants.ShellIconSizes.Large * App.AppModel.AppWindowDPI); - // Ensure thumbnail size is at least 1 to prevent layout errors - thumbnailSize = Math.Max(1, thumbnailSize); - var hr = PInvoke.RoGetAgileReference(AgileReferenceOptions.AGILEREFERENCE_DEFAULT, typeof(IShellItem).GUID, ((IWindowsStorable)Item).ThisPtr, out IAgileReference shellItemReference); - if (hr.ThrowIfFailedOnDebug().Failed) - return; - - var rawThumbnailData = await STATask.RunPooled(() => - { - if (shellItemReference.Resolve(out IShellItem shellItem).ThrowIfFailedOnDebug().Failed) - return null; - - using var folder = new WindowsFolder(shellItem); - folder.TryGetThumbnail(thumbnailSize, SIIGBF.SIIGBF_ICONONLY, out var data); - return data; - }, App.Logger); - if (_isDisposed || rawThumbnailData is null) - return; - - var thumbnail = await rawThumbnailData.ToBitmapAsync(); - if (!_isDisposed) - Thumbnail = thumbnail; - } - - } -} diff --git a/src/Files.App/Data/Items/WidgetFolderCardItem.cs b/src/Files.App/Data/Items/WidgetFolderCardItem.cs index f54a89986256..a6238be961ec 100644 --- a/src/Files.App/Data/Items/WidgetFolderCardItem.cs +++ b/src/Files.App/Data/Items/WidgetFolderCardItem.cs @@ -35,7 +35,6 @@ public WidgetFolderCardItem(IStorable item, string text, string path, bool isPin Tooltip = tooltip; } -#if !WINDOWS /// /// Creates a card for a plain folder path; there is no shell item behind it on Linux. /// @@ -50,13 +49,11 @@ public WidgetFolderCardItem(string path, string text, bool isPinned, string tool Path = path; Tooltip = tooltip; } -#endif private sealed record FolderPath(string Id, string Name) : IStorable; // Methods -#if !WINDOWS public async Task LoadCardThumbnailAsync() { if (_isDisposed || string.IsNullOrEmpty(Path)) @@ -75,7 +72,6 @@ await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => Thumbnail = thumbnail; }); } -#endif public void Dispose() { diff --git a/src/Files.App/Data/Items/WidgetRecentItem.cs b/src/Files.App/Data/Items/WidgetRecentItem.cs index 7cd7a94f3bc8..63e7034c7a34 100644 --- a/src/Files.App/Data/Items/WidgetRecentItem.cs +++ b/src/Files.App/Data/Items/WidgetRecentItem.cs @@ -2,9 +2,6 @@ // SPDX-License-Identifier: MPL-2.0 using Microsoft.UI.Xaml.Media.Imaging; -#if WINDOWS || FILES_WIN32_COMPAT -using Windows.Win32.UI.Shell; -#endif namespace Files.App.Data.Items { @@ -33,12 +30,6 @@ public BitmapImage? Icon ///
public required DateTime LastModified { get; set; } -#if WINDOWS || FILES_WIN32_COMPAT - /// - /// Gets or initializes the Windows shell item of the recent item. - /// - public IShellItem? ShellItem { get; init; } -#endif /// /// Loads thumbnail icon of the recent item. diff --git a/src/Files.App/Data/Items/WindowEx.cs b/src/Files.App/Data/Items/WindowEx.cs deleted file mode 100644 index a2ba5e8d98ed..000000000000 --- a/src/Files.App/Data/Items/WindowEx.cs +++ /dev/null @@ -1,374 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Microsoft.UI.Windowing; -using Microsoft.UI.Xaml; -using System.Runtime.InteropServices; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.Storage; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Gdi; -using Windows.Win32.UI.WindowsAndMessaging; -using WinRT; -using MONITORENUMPROC = Windows.Win32.Extras.ManagedMONITORENUMPROC; -using WNDPROC = Windows.Win32.Extras.ManagedWNDPROC; - -namespace Files.App.Data.Items -{ - /// - /// Represents base class to extend its features. - /// - public unsafe partial class WindowEx : Window, IDisposable - { - private bool _isInitialized; - private bool _isClosing; - private bool _isRestoringPlacement; - private WINDOWPLACEMENT _lastOverlappedPlacement; - private bool _hasOverlappedPlacement; - private readonly nint _oldWndProc; - private readonly WNDPROC _newWndProc; - - private readonly ApplicationDataContainer _applicationDataContainer = ApplicationData.Current.LocalSettings; - - /// - /// Gets hWnd of this . - /// - public nint WindowHandle { get; } - - /// - /// Gets min width of this . - /// - public int MinWidth { get; } - - /// - /// Gets min height of this . - /// - public int MinHeight { get; } - - /// - private bool _IsMaximizable = true; - /// - /// Gets or sets a value that indicates whether this can be maximizable. - /// - public bool IsMaximizable - { - get => _IsMaximizable; - [DynamicWindowsRuntimeCast(typeof(OverlappedPresenter))] - set - { - _IsMaximizable = value; - - if (AppWindow.Presenter is OverlappedPresenter overlapped) - overlapped.IsMaximizable = value; - } - } - - private bool _IsMinimizable = true; - /// - /// Gets or sets a value that indicates whether this can be minimizable. - /// - public bool IsMinimizable - { - get => _IsMinimizable; - [DynamicWindowsRuntimeCast(typeof(OverlappedPresenter))] - set - { - _IsMinimizable = value; - - if (AppWindow.Presenter is OverlappedPresenter overlapped) - overlapped.IsMinimizable = value; - } - } - - /// - /// Initializes class. - /// - /// Min width to set when initialized. - /// Min height to set when initialized. - public unsafe WindowEx(int minWidth = 400, int minHeight = 300) - { - WindowHandle = WinRT.Interop.WindowNative.GetWindowHandle(this); - MinWidth = minWidth; - MinHeight = minHeight; - IsMaximizable = true; - IsMinimizable = true; - - _newWndProc = new(NewWindowProc); - var pNewWndProc = Marshal.GetFunctionPointerForDelegate(_newWndProc); - _oldWndProc = PInvoke.SetWindowLongPtr(new(WindowHandle), WINDOW_LONG_PTR_INDEX.GWL_WNDPROC, pNewWndProc); - - Closed += WindowEx_Closed; - Activated += WindowEx_Activated; - } - - protected virtual bool PersistPlacement => false; - - private unsafe void StoreWindowPlacementData() - { - if (!PersistPlacement) - return; - - // Store monitor info - using var data = new SystemIO.MemoryStream(); - using var sw = new SystemIO.BinaryWriter(data); - - var monitors = GetAllMonitorInfo(); - sw.Write(monitors.Count); - - foreach (var monitor in monitors) - { - sw.Write(monitor.Item1); - sw.Write(monitor.Item2.Left); - sw.Write(monitor.Item2.Top); - sw.Write(monitor.Item2.Right); - sw.Write(monitor.Item2.Bottom); - } - - WINDOWPLACEMENT placement = default; - if (IsOverlappedPresenter()) - PInvoke.GetWindowPlacement(new(WindowHandle), ref placement); - else if (_hasOverlappedPlacement) - // Closing in fullscreen/compact overlay: persist the last overlapped geometry instead - placement = _lastOverlappedPlacement; - else - return; - - int structSize = Marshal.SizeOf(); - IntPtr buffer = Marshal.AllocHGlobal(structSize); - Marshal.StructureToPtr(placement, buffer, false); - byte[] placementData = new byte[structSize]; - Marshal.Copy(buffer, placementData, 0, structSize); - Marshal.FreeHGlobal(buffer); - - sw.Write(placementData); - sw.Flush(); - - var values = GetDataStore(out _, true); - - if (_applicationDataContainer.Containers.ContainsKey("WinUIEx")) - _applicationDataContainer.DeleteContainer("WinUIEx"); - - values["MainWindowPlacementData"] = Convert.ToBase64String(data.ToArray()); - } - - private void RestoreWindowPlacementData() - { - if (!PersistPlacement) - return; - - var values = GetDataStore(out var oldDataExists, false); - - byte[]? data = null; - if (values.TryGetValue(oldDataExists ? "WindowPersistance_FilesMainWindow" : "MainWindowPlacementData", out object? value)) - { - if (value is string base64) - data = Convert.FromBase64String(base64); - } - - if (data is null) - return; - - SystemIO.BinaryReader br = new(new SystemIO.MemoryStream(data)); - - // Check if monitor layout changed since we stored position - var monitors = GetAllMonitorInfo(); - int monitorCount = br.ReadInt32(); - if (monitorCount != monitors.Count) - return; - - for (int i = 0; i < monitorCount; i++) - { - var pMonitor = monitors[i]; - br.ReadString(); - if (pMonitor.Item2.Left != br.ReadDouble() || - pMonitor.Item2.Top != br.ReadDouble() || - pMonitor.Item2.Right != br.ReadDouble() || - pMonitor.Item2.Bottom != br.ReadDouble()) - return; - } - - int structSize = Marshal.SizeOf(); - byte[] placementData = br.ReadBytes(structSize); - IntPtr buffer = Marshal.AllocHGlobal(structSize); - Marshal.Copy(placementData, 0, buffer, structSize); - var windowPlacementData = Marshal.PtrToStructure(buffer); - - Marshal.FreeHGlobal(buffer); - - // Ignore anything by maximized or normal - if (windowPlacementData.showCmd == (SHOW_WINDOW_CMD)0x0002 /*SW_INVALIDATE*/ && - windowPlacementData.flags == WINDOWPLACEMENT_FLAGS.WPF_RESTORETOMAXIMIZED) - windowPlacementData.showCmd = SHOW_WINDOW_CMD.SW_MAXIMIZE; - else if (windowPlacementData.showCmd != SHOW_WINDOW_CMD.SW_MAXIMIZE) - windowPlacementData.showCmd = SHOW_WINDOW_CMD.SW_NORMAL; - - // Suppress DPI-change reflow and min-size clamping while the persisted placement is applied - _isRestoringPlacement = true; - try - { - PInvoke.SetWindowPlacement(new(WindowHandle), in windowPlacementData); - } - finally - { - _isRestoringPlacement = false; - } - } - - private IPropertySet GetDataStore(out bool oldDataExists, bool useNewStore = true) - { - IPropertySet values; - oldDataExists = false; - - if (_applicationDataContainer.Containers.TryGetValue("Files", out var dataContainer)) - { - values = dataContainer.Values; - } - else if (!useNewStore && _applicationDataContainer.Containers.TryGetValue("WinUIEx", out var oldDataContainer)) - { - values = oldDataContainer.Values; - oldDataExists = true; - } - else - { - values = _applicationDataContainer.CreateContainer( - "Files", - ApplicationDataCreateDisposition.Always).Values; - } - - return values; - } - - private unsafe List> GetAllMonitorInfo() - { - List> monitors = []; - - MONITORENUMPROC monitorEnumProc = new((HMONITOR monitor, HDC deviceContext, RECT* rect, LPARAM data) => - { - MONITORINFOEXW info = default; - info.monitorInfo.cbSize = (uint)Marshal.SizeOf(); - - PInvoke.GetMonitorInfo(monitor, (MONITORINFO*)&info); - - monitors.Add(new( - info.szDevice.ToString(), - new(new Point(rect->left, rect->top), new Point(rect->right, rect->bottom)))); - - return true; - }); - - var pMonitorEnumProc = Marshal.GetFunctionPointerForDelegate(monitorEnumProc); - var pfnMonitorEnumProc = (delegate* unmanaged[Stdcall])pMonitorEnumProc; - - LPARAM lParam = default; - BOOL fRes = PInvoke.EnumDisplayMonitors(new(nint.Zero), (RECT*)null, pfnMonitorEnumProc, lParam); - if (!fRes) - Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); - - return monitors; - } - - // Return true to mark the message handled and skip the original window procedure - protected virtual bool OnWindowMessageReceived(uint message, WPARAM wParam, LPARAM lParam, ref LRESULT result) - { - return false; - } - - private bool IsOverlappedPresenter() - { - // COMException when the AppWindow is queried during window teardown - try - { - return AppWindow?.Presenter?.Kind is AppWindowPresenterKind.Overlapped; - } - catch (COMException) - { - return false; - } - } - - private LRESULT NewWindowProc(HWND param0, uint param1, WPARAM param2, LPARAM param3) - { - LRESULT overrideResult = default; - if (OnWindowMessageReceived(param1, param2, param3, ref overrideResult)) - return overrideResult; - - switch (param1) - { - case 0x0018 /*WM_SHOWWINDOW*/ when param2 == (WPARAM)1 && !_isInitialized: - { - _isInitialized = true; - - // A malformed persisted blob (FormatException/EndOfStreamException) must not unwind through the native wndproc - try - { - RestoreWindowPlacementData(); - } - catch (Exception) - { - } - - break; - } - case 0x0024 /*WM_GETMINMAXINFO*/ when !_isRestoringPlacement: - { - var dpi = PInvoke.GetDpiForWindow(param0); - float scalingFactor = (float)dpi / 96; - - var minMaxInfo = Marshal.PtrToStructure(param3); - minMaxInfo.ptMinTrackSize.X = (int)(MinWidth * scalingFactor); - minMaxInfo.ptMinTrackSize.Y = (int)(MinHeight * scalingFactor); - Marshal.StructureToPtr(minMaxInfo, param3, false); - break; - } - case 0x02E0 /*WM_DPICHANGED*/ when _isRestoringPlacement: - { - // Keep the persisted rect: don't let the default handler apply the DPI-suggested rectangle - return default; - } - case 0x0047 /*WM_WINDOWPOSCHANGED*/ when PersistPlacement && IsOverlappedPresenter(): - { - WINDOWPLACEMENT placement = default; - PInvoke.GetWindowPlacement(param0, ref placement); - _lastOverlappedPlacement = placement; - _hasOverlappedPlacement = true; - break; - } - } - - var pfnOldWndProc = (delegate* unmanaged[Stdcall])_oldWndProc; - - return PInvoke.CallWindowProc(pfnOldWndProc, param0, param1, param2, param3); - } - - private void WindowEx_Closed(object sender, WindowEventArgs args) - { - _isClosing = true; - - // A LocalSettings write failure (COMException/UnauthorizedAccessException) must not crash the close path - try - { - StoreWindowPlacementData(); - } - catch (Exception) - { - } - } - - private void WindowEx_Activated(object sender, WindowActivatedEventArgs args) - { - if (args.WindowActivationState is not WindowActivationState.Deactivated) - _isClosing = false; - - if (!_isClosing && SystemBackdrop is AppSystemBackdrop appSystemBackdrop) - appSystemBackdrop.SetInputActive(args.WindowActivationState is not WindowActivationState.Deactivated); - } - - public void Dispose() - { - Closed -= WindowEx_Closed; - Activated -= WindowEx_Activated; - } - } -} diff --git a/src/Files.App/Data/Items/WindowMessageMonitor.cs b/src/Files.App/Data/Items/WindowMessageMonitor.cs deleted file mode 100644 index 9901c9de54c7..000000000000 --- a/src/Files.App/Data/Items/WindowMessageMonitor.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.WindowsAndMessaging; -using WNDPROC = Windows.Win32.Extras.ManagedWNDPROC; - -namespace Files.App.Data.Items -{ - public readonly struct WindowMessage - { - public uint MessageId { get; init; } - public nuint WParam { get; init; } - public nint LParam { get; init; } - } - - public sealed class WindowMessageEventArgs : EventArgs - { - public WindowMessage Message { get; init; } - - // When true the original window procedure is skipped and Result is returned - public bool Handled { get; set; } - - public nint Result { get; set; } - } - - /// - /// Monitors window messages of an arbitrary window by subclassing its window procedure. - /// - public sealed unsafe partial class WindowMessageMonitor : IDisposable - { - private readonly HWND _hwnd; - private readonly WNDPROC _newWndProc; - private readonly nint _oldWndProc; - private bool _disposed; - - public event EventHandler? WindowMessageReceived; - - public WindowMessageMonitor(HWND hwnd) - { - _hwnd = hwnd; - - _newWndProc = new(NewWindowProc); - var pNewWndProc = Marshal.GetFunctionPointerForDelegate(_newWndProc); - _oldWndProc = PInvoke.SetWindowLongPtr(hwnd, WINDOW_LONG_PTR_INDEX.GWL_WNDPROC, pNewWndProc); - } - - private LRESULT NewWindowProc(HWND param0, uint param1, WPARAM param2, LPARAM param3) - { - if (WindowMessageReceived is { } handler) - { - var args = new WindowMessageEventArgs - { - Message = new() { MessageId = param1, WParam = param2.Value, LParam = param3.Value }, - }; - - // A subscriber exception must not unwind through the native window procedure (fail-fast under AOT) - try - { - handler(this, args); - } - catch (Exception ex) - { - Debug.WriteLine(ex); - } - - if (args.Handled) - return new(args.Result); - } - - var pfnOldWndProc = (delegate* unmanaged[Stdcall])_oldWndProc; - - return PInvoke.CallWindowProc(pfnOldWndProc, param0, param1, param2, param3); - } - - public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - - PInvoke.SetWindowLongPtr(_hwnd, WINDOW_LONG_PTR_INDEX.GWL_WNDPROC, _oldWndProc); - } - } -} diff --git a/src/Files.App/Data/Models/AppModel.cs b/src/Files.App/Data/Models/AppModel.cs index 2604515919c9..f4b48c16f08f 100644 --- a/src/Files.App/Data/Models/AppModel.cs +++ b/src/Files.App/Data/Models/AppModel.cs @@ -4,10 +4,6 @@ using Microsoft.UI.Xaml.Controls; using System.Runtime.InteropServices; using Windows.ApplicationModel.DataTransfer; -#if WINDOWS -using Windows.Win32; -using Windows.Win32.Foundation; -#endif using WinRT; namespace Files.App.Data.Models @@ -147,16 +143,11 @@ public float AppWindowDPI { if (_AppWindowDPI is null || _AppWindowDPI == 0f) { -#if WINDOWS - var dpi = PInvoke.GetDpiForWindow((HWND)MainWindow.Instance.WindowHandle); - _AppWindowDPI = dpi > 0 ? dpi / 96f : 1.0f; // Fallback to 1.0f if invalid DPI -#else // Not cached until the window content exists, so early callers do not pin 1.0 var scale = (float?)MainWindow.Instance?.Content?.XamlRoot?.RasterizationScale; if (scale is null or <= 0f) return 1.0f; _AppWindowDPI = scale; -#endif } return _AppWindowDPI.Value; } diff --git a/src/Files.App/Data/Models/CompressArchiveModel.Windows.cs b/src/Files.App/Data/Models/CompressArchiveModel.Windows.cs deleted file mode 100644 index 303a24807ede..000000000000 --- a/src/Files.App/Data/Models/CompressArchiveModel.Windows.cs +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Utils.Storage.Operations; -using Microsoft.Extensions.Logging; -using SevenZip; -using System.IO; - -namespace Files.App.Data.Models -{ - /// - /// Provides an archive creation support. - /// - public sealed class CompressArchiveModel : ICompressArchiveModel - { - private StatusCenterItemProgressModel? _fileSystemProgress; - - private FileSizeCalculator? _sizeCalculator; - - private string ArchiveExtension => FileFormat switch - { - ArchiveFormats.Zip => ".zip", - ArchiveFormats.SevenZip => ".7z", - ArchiveFormats.Tar => ".tar", - ArchiveFormats.GZip => ".gz", - _ => throw new ArgumentOutOfRangeException(nameof(FileFormat)), - }; - - private OutArchiveFormat SevenZipArchiveFormat => FileFormat switch - { - ArchiveFormats.Zip => OutArchiveFormat.Zip, - ArchiveFormats.SevenZip => OutArchiveFormat.SevenZip, - ArchiveFormats.Tar => OutArchiveFormat.Tar, - ArchiveFormats.GZip => OutArchiveFormat.GZip, - _ => throw new ArgumentOutOfRangeException(nameof(FileFormat)), - }; - - private CompressionLevel SevenZipCompressionLevel => CompressionLevel switch - { - ArchiveCompressionLevels.Ultra => SevenZip.CompressionLevel.Ultra, - ArchiveCompressionLevels.High => SevenZip.CompressionLevel.High, - ArchiveCompressionLevels.Normal => SevenZip.CompressionLevel.Normal, - ArchiveCompressionLevels.Low => SevenZip.CompressionLevel.Low, - ArchiveCompressionLevels.Fast => SevenZip.CompressionLevel.Fast, - ArchiveCompressionLevels.None => SevenZip.CompressionLevel.None, - _ => throw new ArgumentOutOfRangeException(nameof(CompressionLevel)), - }; - - private long SevenZipVolumeSize => SplittingSize switch - { - ArchiveSplittingSizes.None => 0L, - ArchiveSplittingSizes.Mo10 => 10 * 1000 * 1000L, - ArchiveSplittingSizes.Mo100 => 100 * 1000 * 1000L, - ArchiveSplittingSizes.Mo1024 => 1024 * 1000 * 1000L, - ArchiveSplittingSizes.Mo2048 => 2048 * 1000 * 1000L, - ArchiveSplittingSizes.Mo5120 => 5120 * 1000 * 1000L, - ArchiveSplittingSizes.Fat4092 => 4092 * 1000 * 1000L, - ArchiveSplittingSizes.Cd650 => 650 * 1000 * 1000L, - ArchiveSplittingSizes.Cd700 => 700 * 1000 * 1000L, - ArchiveSplittingSizes.Dvd4480 => 4480 * 1000 * 1000L, - ArchiveSplittingSizes.Dvd8128 => 8128 * 1000 * 1000L, - ArchiveSplittingSizes.Bd23040 => 23040 * 1000 * 1000L, - _ => throw new ArgumentOutOfRangeException(nameof(SplittingSize)), - }; - - private IProgress? _Progress; - public IProgress? Progress - { - get => _Progress; - set - { - _Progress = value; - _fileSystemProgress = new( - value, - false, - FileSystemStatusCode.InProgress); - - _fileSystemProgress.Report(0); - } - } - - /// - public string ArchivePath { get; set; } - - /// - public string Directory { get; init; } - - /// - public string FileName { get; init; } - - /// - public string Password { get; init; } - - /// - public IEnumerable Sources { get; init; } - - /// - public ArchiveFormats FileFormat { get; init; } - - /// - public ArchiveCompressionLevels CompressionLevel { get; init; } - - /// - public ArchiveSplittingSizes SplittingSize { get; init; } - - /// - public ArchiveDictionarySizes DictionarySize { get; init; } - - /// - public ArchiveWordSizes WordSize { get; init; } - - /// - public CancellationToken CancellationToken { get; set; } - - /// - public bool IsCancelled { get; private set; } - - /// - public int CPUThreads { get; set; } - - public CompressArchiveModel( - string[] source, - string directory, - string fileName, - int cpuThreads, - string? password = null, - ArchiveFormats fileFormat = ArchiveFormats.Zip, - ArchiveCompressionLevels compressionLevel = ArchiveCompressionLevels.Normal, - ArchiveSplittingSizes splittingSize = ArchiveSplittingSizes.None, - ArchiveDictionarySizes dictionarySize = ArchiveDictionarySizes.Auto, - ArchiveWordSizes wordSize = ArchiveWordSizes.Auto) - { - _Progress = new Progress(); - - Sources = source; - Directory = directory; - FileName = fileName; - Password = password ?? string.Empty; - ArchivePath = string.Empty; - FileFormat = fileFormat; - CompressionLevel = compressionLevel; - SplittingSize = splittingSize; - DictionarySize = dictionarySize; - WordSize = wordSize; - CPUThreads = cpuThreads; - } - - /// - public string GetArchivePath(string suffix = "") - { - return Path.Combine(Directory, $"{FileName}{suffix}{ArchiveExtension}"); - } - - /// - public async Task RunCreationAsync() - { - if (_fileSystemProgress is null) - throw new InvalidOperationException("Compression progress must be initialized before archive creation starts."); - - string[] sources = Sources.ToArray(); - - var compressor = new SevenZipCompressor() - { - ArchiveFormat = SevenZipArchiveFormat, - CompressionLevel = SevenZipCompressionLevel, - VolumeSize = FileFormat is ArchiveFormats.SevenZip ? SevenZipVolumeSize : 0, - FastCompression = false, - IncludeEmptyDirectories = true, - EncryptHeaders = true, - PreserveDirectoryRoot = sources.Length > 1, - }; - - compressor.CustomParameters.Add("mt", CPUThreads.ToString()); - // Use UTF-8 encoding. - // References: 7-zip chm --> Command Line Version --> Switches - // --> -m --> cu=[off | on]. - // Don't add "cu" parameter for 7zip files, see https://github.com/files-community/Files/issues/17257 - if (FileFormat != ArchiveFormats.SevenZip) - compressor.CustomParameters.Add("cu", "on"); - - if (FileFormat is ArchiveFormats.SevenZip) - { - var dictParam = GetDictionarySizeParam(); - if (dictParam is not null) - compressor.CustomParameters.Add("d", dictParam); - - var wordParam = GetWordSizeParam(); - if (wordParam is not null) - compressor.CustomParameters.Add("fb", wordParam); - } - - compressor.Compressing += Compressor_Compressing; - compressor.FileCompressionStarted += Compressor_FileCompressionStarted; - compressor.FileCompressionFinished += Compressor_FileCompressionFinished; - - var cts = new CancellationTokenSource(); - - try - { - var files = sources.Where(File.Exists).ToArray(); - var directories = sources.Where(SystemIO.Directory.Exists); - var skippedItems = new List(); - - _sizeCalculator = new FileSizeCalculator([.. files, .. directories]); - var sizeTask = _sizeCalculator.ComputeSizeAsync(cts.Token); - _ = sizeTask.ContinueWith(_ => - { - _fileSystemProgress.TotalSize = _sizeCalculator.Size; - _fileSystemProgress.ItemsCount = _sizeCalculator.ItemsCount; - _fileSystemProgress.EnumerationCompleted = true; - _fileSystemProgress.Report(); - }); - - // Enumerate the sources ourselves, skipping items that cannot be - // archived (e.g. broken junctions or locked files), see #16240 - var directoryItems = new List<(string Path, List ArchivableItems)>(); - var archivableFiles = new List(); - - await Task.Run(() => - { - foreach (string directory in directories) - { - var directoryPath = Path.GetFullPath(directory); - var archivableItems = new List(); - - AddArchivableItems(directoryPath, archivableItems, skippedItems); - directoryItems.Add((directoryPath, archivableItems)); - } - - foreach (var file in files) - { - if (CanOpenFile(file)) - archivableFiles.Add(file); - else - skippedItems.Add(file); - } - }); - - if (skippedItems.Count > 0) - { - var logger = Ioc.Default.GetRequiredService>(); - logger?.LogWarning($"Skipped {skippedItems.Count} item(s) that could not be archived to {LogPathHelper.RedactPath(ArchivePath)}: {string.Join(", ", skippedItems.Select(LogPathHelper.RedactPath))}"); - - // Ask the user whether to skip the items or cancel the operation, see #16240 - var dialogService = Ioc.Default.GetRequiredService(); - var dialogResult = await dialogService.ShowDialogAsync(new CompressSkippedItemsDialogViewModel(skippedItems)); - - if (dialogResult is not DialogResult.Primary) - { - IsCancelled = true; - cts.Cancel(); - - return false; - } - } - - foreach ((string directoryPath, List archivableItems) in directoryItems) - { - if (archivableItems.Any(File.Exists)) - { - var commonRootLength = GetCommonRootLength(directoryPath, sources.Length > 1); - - if (string.IsNullOrEmpty(Password)) - await compressor.CompressFilesAsync(ArchivePath, commonRootLength, [.. archivableItems]); - else - await compressor.CompressFilesEncryptedAsync(ArchivePath, commonRootLength, Password, [.. archivableItems]); - } - else - { - // The directory has no files, so we need to create entries manually - var fileDictionary = new Dictionary(); - AddEntry(fileDictionary, directoryPath, ""); - - compressor.CompressFileDictionary(fileDictionary, ArchivePath, Password); - - static void AddEntry(IDictionary fileDictionary, string directory, string entryPrefix) - { - DirectoryInfo directoryInfo = new DirectoryInfo(directory); - - DirectoryInfo[] directories; - - try - { - directories = directoryInfo.GetDirectories(); - } - catch (Exception) - { - // The directory contents are inaccessible (e.g. a broken junction), skip it - return; - } - - if (directories.Length == 0) - { - AddArchiveEntry(fileDictionary, entryPrefix + directoryInfo.Name, null); - } - else - { - entryPrefix += directoryInfo.Name + Path.DirectorySeparatorChar; - foreach (DirectoryInfo directoryInfo2 in directories) - AddEntry(fileDictionary, directoryInfo2.FullName, entryPrefix); - } - } - - // SevenZipSharp uses a null source path to represent an empty directory. - static void AddArchiveEntry(IDictionary entries, string name, string? sourcePath) - => entries.Add(name, sourcePath!); - } - - compressor.CompressionMode = CompressionMode.Append; - } - - if (archivableFiles.Count > 0) - { - if (string.IsNullOrEmpty(Password)) - await compressor.CompressFilesAsync(ArchivePath, [.. archivableFiles]); - else - await compressor.CompressFilesEncryptedAsync(ArchivePath, Password, [.. archivableFiles]); - } - - cts.Cancel(); - - return true; - } - catch (Exception ex) - { - var logger = Ioc.Default.GetRequiredService>(); - logger?.LogWarning(ex, $"Error compressing folder: {LogPathHelper.RedactPath(ArchivePath)}"); - - cts.Cancel(); - - return false; - } - } - - /// - /// Recursively collects the items of a directory that can be archived, - /// skipping items that cannot be read (e.g. broken junctions or locked files). - /// - private void AddArchivableItems(string directory, List items, List skippedItems) - { - CancellationToken.ThrowIfCancellationRequested(); - - FileSystemInfo[] children; - - try - { - children = new DirectoryInfo(directory).GetFileSystemInfos(); - } - catch (Exception) - { - // The directory contents are inaccessible (e.g. a broken junction or access denied) - skippedItems.Add(directory); - return; - } - - foreach (var child in children) - { - if (child is DirectoryInfo) - { - // Add the directory entry itself so empty directories are preserved - items.Add(child.FullName); - AddArchivableItems(child.FullName, items, skippedItems); - } - else if (CanOpenFile(child.FullName)) - { - items.Add(child.FullName); - } - else - { - skippedItems.Add(child.FullName); - } - } - } - - private static bool CanOpenFile(string path) - { - try - { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - - return true; - } - catch (Exception) - { - return false; - } - } - - private static int GetCommonRootLength(string directoryPath, bool preserveRootEntry) - { - // Entries are relative to the directory itself unless the root should be preserved - var trimmedPath = directoryPath.TrimEnd(Path.DirectorySeparatorChar); - var root = preserveRootEntry ? Path.GetDirectoryName(trimmedPath) : trimmedPath; - - return string.IsNullOrEmpty(root) - ? trimmedPath.Length + 1 - : root.TrimEnd(Path.DirectorySeparatorChar).Length + 1; - } - - private void Compressor_FileCompressionStarted(object? sender, FileNameEventArgs e) - { - if (CancellationToken.IsCancellationRequested) - { - e.Cancel = true; - return; - } - - _sizeCalculator!.ForceComputeFileSize(e.FilePath); - _fileSystemProgress!.FileName = e.FileName; - _fileSystemProgress.Report(); - } - - private void Compressor_FileCompressionFinished(object? sender, EventArgs e) - { - _fileSystemProgress!.AddProcessedItemsCount(1); - _fileSystemProgress.Report(); - } - - private void Compressor_Compressing(object? _, ProgressEventArgs e) - { - if (_fileSystemProgress!.TotalSize > 0) - _fileSystemProgress.Report((_fileSystemProgress.ProcessedSize + e.PercentDelta / 100.0 * e.BytesCount) / _fileSystemProgress.TotalSize * 100); - } - - private string? GetDictionarySizeParam() => DictionarySize switch - { - ArchiveDictionarySizes.Auto => null, - ArchiveDictionarySizes.Kb64 => "64k", - ArchiveDictionarySizes.Kb256 => "256k", - ArchiveDictionarySizes.Mb1 => "1m", - ArchiveDictionarySizes.Mb2 => "2m", - ArchiveDictionarySizes.Mb4 => "4m", - ArchiveDictionarySizes.Mb8 => "8m", - ArchiveDictionarySizes.Mb16 => "16m", - ArchiveDictionarySizes.Mb32 => "32m", - ArchiveDictionarySizes.Mb64 => "64m", - ArchiveDictionarySizes.Mb128 => "128m", - ArchiveDictionarySizes.Mb256 => "256m", - ArchiveDictionarySizes.Mb512 => "512m", - ArchiveDictionarySizes.Mb1024 => "1024m", - _ => null, - }; - - private string? GetWordSizeParam() => WordSize switch - { - ArchiveWordSizes.Auto => null, - ArchiveWordSizes.Fb8 => "8", - ArchiveWordSizes.Fb16 => "16", - ArchiveWordSizes.Fb32 => "32", - ArchiveWordSizes.Fb64 => "64", - ArchiveWordSizes.Fb128 => "128", - ArchiveWordSizes.Fb256 => "256", - ArchiveWordSizes.Fb273 => "273", - _ => null, - }; - } -} diff --git a/src/Files.App/Data/Models/CompressArchiveModel.cs b/src/Files.App/Data/Models/CompressArchiveModel.cs index 8c7c579bd07c..58aa9272c62b 100644 --- a/src/Files.App/Data/Models/CompressArchiveModel.cs +++ b/src/Files.App/Data/Models/CompressArchiveModel.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Archives; using System.IO; @@ -159,4 +158,3 @@ public async Task RunCreationAsync() } } -#endif diff --git a/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModel.cs b/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModel.cs index 35757a8cd215..6deaf0664d88 100644 --- a/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModel.cs +++ b/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModel.cs @@ -48,20 +48,16 @@ public sealed class ContextMenuFlyoutItemViewModel public KeyboardAccelerator? KeyboardAccelerator { get; set; } -#if !WINDOWS public VirtualKey? KeyboardAcceleratorKey { get; set; } public VirtualKeyModifiers KeyboardAcceleratorModifiers { get; set; } -#endif internal KeyboardAccelerator? CreateKeyboardAccelerator() { if (KeyboardAccelerator is { } accelerator) return new() { Key = accelerator.Key, Modifiers = accelerator.Modifiers }; -#if !WINDOWS if (KeyboardAcceleratorKey is { } key) return new() { Key = key, Modifiers = KeyboardAcceleratorModifiers }; -#endif return null; } diff --git a/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModelBuilder.cs b/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModelBuilder.cs index 879127d6b106..69f53426692f 100644 --- a/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModelBuilder.cs +++ b/src/Files.App/Data/Models/ContextMenuFlyoutItemViewModelBuilder.cs @@ -89,13 +89,8 @@ public ContextMenuFlyoutItemViewModel Build() viewModel.GlyphFontFamilyName = glyph.FontFamily; } -#if WINDOWS - if (command.Key is { } key) - viewModel.KeyboardAccelerator = new Microsoft.UI.Xaml.Input.KeyboardAccelerator { Key = key, Modifiers = command.Modifiers }; -#else viewModel.KeyboardAcceleratorKey = command.Key; viewModel.KeyboardAcceleratorModifiers = command.Modifiers; -#endif viewModel.KeyboardAcceleratorTextOverride = command.HotKeyLabel; return viewModel; diff --git a/src/Files.App/Data/Models/DrivesViewModel.cs b/src/Files.App/Data/Models/DrivesViewModel.cs index f8cc3cb51aeb..b5ccb02ba24b 100644 --- a/src/Files.App/Data/Models/DrivesViewModel.cs +++ b/src/Files.App/Data/Models/DrivesViewModel.cs @@ -112,29 +112,6 @@ public async Task UpdateDrivesAsync() InsertSorted(item); } -#if WINDOWS - // The broad file system access consent (ms-settings) only exists on Windows - var osDrive = await removableDrivesService.GetPrimaryDriveAsync(); - - // Show consent dialog if the OS drive could not be accessed - if (osDrive is null) - { - ShowUserConsentOnInit = true; - } - else - { - var osDrivePath = osDrive.Id.EndsWith(Path.DirectorySeparatorChar) - ? osDrive.Id - : $"{osDrive.Id}{Path.DirectorySeparatorChar}"; - - bool isOsDriveMissing; - lock (Drives) - isOsDriveMissing = Drives.All(x => string.IsNullOrEmpty(x.Id) || !Path.GetFullPath(x.Id).Equals(osDrivePath, StringComparison.OrdinalIgnoreCase)); - - if (isOsDriveMissing) - ShowUserConsentOnInit = true; - } -#endif if (watcher.CanBeStarted) watcher.Start(); diff --git a/src/Files.App/Data/Models/PinnedFoldersManager.cs b/src/Files.App/Data/Models/PinnedFoldersManager.cs index e554549babb2..cac0576d11ac 100644 --- a/src/Files.App/Data/Models/PinnedFoldersManager.cs +++ b/src/Files.App/Data/Models/PinnedFoldersManager.cs @@ -4,9 +4,6 @@ using Microsoft.Extensions.Logging; using System.Collections.Specialized; using System.IO; -#if WINDOWS -using Windows.Win32.UI.Shell; -#endif namespace Files.App.Data.Models { @@ -140,17 +137,8 @@ public async Task CreateLocationItemFromPathAsync(string path) private static string? GetLibraryDisplayName(string libraryPath) { -#if !WINDOWS // Windows libraries (.library-ms) don't exist on Linux return null; -#else - using var storable = WindowsStorable.TryParse(libraryPath); - if (storable is null) - return null; - - var displayName = storable.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY); - return string.IsNullOrEmpty(displayName) ? null : displayName; -#endif } private async Task LoadIconForLocationItemAsync(LocationItem locationItem, string path, bool isFolder = true) @@ -183,15 +171,7 @@ private async Task LoadRecycleBinIconAsync(LocationItem locationItem) { try { -#if WINDOWS - var icon = await FileThumbnailHelper.GetIconAsync( - Constants.UserEnvironmentPaths.RecycleBinPath, - Constants.ShellIconSizes.Small, - true, - IconOptions.ReturnIconOnly | IconOptions.SkipSizeSnapping); -#else var icon = await DriveHelpers.GetDriveIconAsync(null, Constants.ShellIconSizes.Small); -#endif icon ??= UIHelpers.GetSidebarIconResourceInfo(Constants.ImageRes.RecycleBin)?.IconData; await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => diff --git a/src/Files.App/Data/Models/RemovableDevice.Windows.cs b/src/Files.App/Data/Models/RemovableDevice.Windows.cs deleted file mode 100644 index 76fcee4b74de..000000000000 --- a/src/Files.App/Data/Models/RemovableDevice.Windows.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; -using static Files.App.Helpers.Win32PInvoke; - -namespace Files.App.Data.Models -{ - public sealed class RemovableDevice - { - private nint handle; - private char driveLetter; - - public RemovableDevice(string letter) - { - driveLetter = letter[0]; - - string filename = @"\\.\" + driveLetter + ":"; - - handle = CreateFileFromAppW(filename, - (uint)(FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE), - FILE_SHARE_READ | FILE_SHARE_WRITE, - nint.Zero, OPEN_EXISTING, 0, nint.Zero); - } - - public async Task EjectAsync() - { - bool result = false; - - if (handle.ToInt32() == INVALID_HANDLE_VALUE) - { - Debug.WriteLine($"Unable to open drive {driveLetter}"); - return false; - } - - if (await LockVolumeAsync() && DismountVolume()) - { - PreventRemovalOfVolume(false); - result = AutoEjectVolume(); - } - - CloseVolume(); - - return result; - } - - private async Task LockVolumeAsync() - { - bool result = false; - - for (int i = 0; i < 5; i++) - { - if (DeviceIoControl(handle, PInvoke.FSCTL_LOCK_VOLUME, nint.Zero, 0, nint.Zero, 0, out _, nint.Zero)) - { - Debug.WriteLine("Lock successful!"); - result = true; - - break; - } - else - { - Debug.WriteLine($"Can't lock device, attempt {i + 1}, trying again... "); - } - - await Task.Delay(500); - } - - return result; - } - - private bool DismountVolume() - { - return DeviceIoControl(handle, PInvoke.FSCTL_DISMOUNT_VOLUME, nint.Zero, 0, nint.Zero, 0, out _, nint.Zero); - } - - private bool PreventRemovalOfVolume(bool prevent) - { - byte[] buf = [prevent ? (byte)1 : (byte)0]; - return DeviceIoControl(handle, IOCTL_STORAGE_MEDIA_REMOVAL, buf, 1, nint.Zero, 0, out _, nint.Zero); - } - - private bool AutoEjectVolume() - { - return DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, nint.Zero, 0, nint.Zero, 0, out _, nint.Zero); - } - - private bool CloseVolume() - { - return CloseHandle(handle); - } - } -} diff --git a/src/Files.App/Data/Models/SignatureInfoItem.Windows.cs b/src/Files.App/Data/Models/SignatureInfoItem.Windows.cs deleted file mode 100644 index 6b5e8ffc5022..000000000000 --- a/src/Files.App/Data/Models/SignatureInfoItem.Windows.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Utils.Signatures; -using System.Windows.Input; -using Windows.Win32.Foundation; - -namespace Files.App.Data.Models -{ - public sealed partial class SignatureInfoItem : ObservableObject - { - private readonly string _fileName; - - private readonly HWND _hwndParent; - - private readonly int _index; - - private string _Version = string.Empty; - public string Version - { - get => _Version; - set => SetProperty(ref _Version, value); - } - - private string _IssuedBy = string.Empty; - public string IssuedBy - { - get => _IssuedBy; - set => SetProperty(ref _IssuedBy, value); - } - - private string _IssuedTo = string.Empty; - public string IssuedTo - { - get => _IssuedTo; - set => SetProperty(ref _IssuedTo, value); - } - - private string _ValidFromTimestamp = string.Empty; - public string ValidFromTimestamp - { - get => _ValidFromTimestamp; - set => SetProperty(ref _ValidFromTimestamp, value); - } - - private string _ValidToTimestamp = string.Empty; - public string ValidToTimestamp - { - get => _ValidToTimestamp; - set => SetProperty(ref _ValidToTimestamp, value); - } - - private string _VerifiedTimestamp = string.Empty; - public string VerifiedTimestamp - { - get => _VerifiedTimestamp; - set => SetProperty(ref _VerifiedTimestamp, value); - } - - private bool _Verified = false; - public bool Verified - { - get => _Verified; - set - { - if (SetProperty(ref _Verified, value)) - OnPropertyChanged(nameof(Glyph)); - } - } - - public List SignChain { get; } - - public string Glyph => Verified ? "\uE930" : "\uEA39"; - - public ICommand OpenDetailsCommand { get; } - - public SignatureInfoItem(string fileName, int index, HWND hWnd, List chain) - { - _fileName = fileName; - _hwndParent = hWnd; - _index = index; - SignChain = chain ?? new List(); - OpenDetailsCommand = new AsyncRelayCommand(DoOpenDetails); - } - - private Task DoOpenDetails() - { - DigitalSignaturesUtil.DisplaySignerInfoDialog(_fileName, _hwndParent, _index); - return Task.CompletedTask; - } - } -} diff --git a/src/Files.App/Dialogs/LinuxOpenWithDialog.cs b/src/Files.App/Dialogs/LinuxOpenWithDialog.cs index 78e0d16afb70..9d23da40eee5 100644 --- a/src/Files.App/Dialogs/LinuxOpenWithDialog.cs +++ b/src/Files.App/Dialogs/LinuxOpenWithDialog.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Launching; using Files.Platform.Abstractions.Mime; using Microsoft.UI.Xaml; @@ -77,4 +76,3 @@ private static async Task LoadIconAsync(Image image, DesktopApplication app) } } } -#endif diff --git a/src/Files.App/Extensions/FileSecurityResultExtensions.Windows.cs b/src/Files.App/Extensions/FileSecurityResultExtensions.Windows.cs deleted file mode 100644 index c5a890b5f018..000000000000 --- a/src/Files.App/Extensions/FileSecurityResultExtensions.Windows.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Win32.Foundation; - -namespace Files.App.Extensions -{ - /// - /// Converts Win32 error codes from the security APIs to . - /// - public static class FileSecurityResultExtensions - { - /// - /// Converts a Win32 error code to a ; unknown errors map to . - /// - public static FileSecurityResult ToFileSecurityResult(this WIN32_ERROR error) - { - return error switch - { - WIN32_ERROR.ERROR_SUCCESS => FileSecurityResult.Success, - WIN32_ERROR.ERROR_ACCESS_DENIED or WIN32_ERROR.ERROR_PRIVILEGE_NOT_HELD => FileSecurityResult.AccessDenied, - WIN32_ERROR.ERROR_FILE_NOT_FOUND or WIN32_ERROR.ERROR_PATH_NOT_FOUND => FileSecurityResult.NotFound, - WIN32_ERROR.ERROR_WRITE_PROTECT => FileSecurityResult.ReadOnly, - WIN32_ERROR.ERROR_INVALID_ACL or WIN32_ERROR.ERROR_INVALID_SECURITY_DESCR => FileSecurityResult.InvalidAcl, - WIN32_ERROR.ERROR_NOT_SUPPORTED or WIN32_ERROR.ERROR_CALL_NOT_IMPLEMENTED => FileSecurityResult.NotSupported, - _ => FileSecurityResult.Failed, - }; - } - } -} diff --git a/src/Files.App/Extensions/ShellNewEntryExtensions.cs b/src/Files.App/Extensions/ShellNewEntryExtensions.cs index 77eca697b6bc..f7e314dd7b87 100644 --- a/src/Files.App/Extensions/ShellNewEntryExtensions.cs +++ b/src/Files.App/Extensions/ShellNewEntryExtensions.cs @@ -8,25 +8,6 @@ namespace Files.App.Extensions { public static class ShellNewEntryExtensions { -#if WINDOWS || FILES_WIN32_COMPAT - public static async Task> GetNewContextMenuEntries() - { - var shellEntryList = new List(); - - var entries = await SafetyExtensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntries(), App.Logger); - if (entries is not null) - { - shellEntryList.AddRange(entries); - } - - return shellEntryList; - } - - public static async Task GetNewContextMenuEntryForType(string extension) - { - return await SafetyExtensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntryForType(extension), App.Logger); - } -#endif public static async Task> Create(this ShellNewEntry shellEntry, string filePath, IShellPage associatedInstance) { diff --git a/src/Files.App/Extensions/Win32FindDataExtensions.cs b/src/Files.App/Extensions/Win32FindDataExtensions.cs deleted file mode 100644 index 1cf74165364a..000000000000 --- a/src/Files.App/Extensions/Win32FindDataExtensions.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; - -namespace Files.App.Extensions -{ - public static class Win32FindDataExtensions - { - private const long MAX_DWORD = 4294967295; - - public static long GetSize(this Win32PInvoke.WIN32_FIND_DATA findData) - { - long fDataFSize = findData.nFileSizeLow; - - return - fDataFSize + - (fDataFSize < 0 ? MAX_DWORD + 1 : 0) + - (findData.nFileSizeHigh > 0 ? findData.nFileSizeHigh * (MAX_DWORD + 1) : 0); - } - - public static long GetSize(this WIN32_FIND_DATAW findData) - { - long fDataFSize = findData.nFileSizeLow; - - return - fDataFSize + - (fDataFSize < 0 ? MAX_DWORD + 1 : 0) + - (findData.nFileSizeHigh > 0 ? findData.nFileSizeHigh * (MAX_DWORD + 1) : 0); - } - - public static DateTime ToDateTime(this SYSTEMTIME value) - => new(value.wYear, value.wMonth, value.wDay, value.wHour, value.wMinute, value.wSecond, value.wMilliseconds, DateTimeKind.Utc); - } -} diff --git a/src/Files.App/Files.App.csproj b/src/Files.App/Files.App.csproj index a2ac71e96b40..53ae23608c90 100644 --- a/src/Files.App/Files.App.csproj +++ b/src/Files.App/Files.App.csproj @@ -13,44 +13,12 @@ Debug;Release Assets\AppTiles\Dev\Logo.ico true - - true true false SkiaRenderer - - - true - WinExe - Scale|DXFeatureLevel - Language=en-US;af;ar;be-BY;bg;ca;cs-CZ;da;de-DE;el;en-GB;es-ES;es-419;fa-IR;fi-FI;fil-PH;fr-FR;he-IL;hi-IN;hr-HR;hu-HU;hy-AM;id-ID;it-IT;ja-JP;ka;km-KH;ko-KR;lt-LT;lv-LV;ms-MY;nb-NO;nl-NL;pl-PL;pt-BR;pt-PT;ro-RO;ru-RU;sk-SK;sq-AL;sr-Cyrl;sv-SE;ta;th-TH;tr-TR;uk-UA;vi;zh-Hans;zh-Hant - $(MinimalWindowsVersion) - False - SHA256 - False - False - Always - False - x86|x64|arm64 - 0 - app.manifest - win-x86;win-x64;win-arm64 - true - true - false - Microsoft.UI.Content.ContentExternalOutputLink;Microsoft.UI.Content.IContentExternalOutputLink - bin\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\publish\ - False - True - True - true - true - true - - 0.1.0-alpha4 @@ -82,38 +50,6 @@ true - - - - - - - - - - - - - - - - - <_WindowsAppRuntimeBootstrapLibrary Include="@(WindowsAppSdkComponentPackages->'%(FullPath)lib\native\$(Platform)\Microsoft.WindowsAppRuntime.Bootstrap.lib')" /> - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - @@ -149,24 +85,6 @@ - - - - - - - - - - - - - - - - - - @@ -176,14 +94,6 @@ - - - - - - - - @@ -197,46 +107,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(DefaultItemExcludes);Assets/Libraries/**;Assets/FilesOpenDialog/**;Assets/WSL/**;Assets/tile-0-*.png;Assets/AppTiles/**/*.png @@ -245,67 +115,14 @@ - - - $(DefaultItemExcludes);UserControls/FilePreviews/ShellPreview.xaml;UserControls/FilePreviews/CodePreview.xaml;UserControls/FilePreviews/MarkdownPreview.xaml;UserControls/FilePreviews/TextPreview.xaml - - - - $(DefaultItemExcludes);UserControls/FilePreviews/DesktopTextPreview.xaml - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - $(DefaultItemExcludes);Views/Properties/SecurityPage.xaml;Views/Properties/SecurityAdvancedPage.xaml;Views/Properties/SignaturesPage.xaml;Views/Properties/CompatibilityPage.xaml;Views/Properties/CustomizationPage.xaml - - - - - $(DefineConstants);FILES_WIN32_COMPAT - - - - ..\Files.App.CsWin32\bin\x64\$(Configuration)\$(WindowsTargetFramework)\Files.App.CsWin32.dll - - - - - - - diff --git a/src/Files.App/GlobalUsings.cs b/src/Files.App/GlobalUsings.cs index eee0d9af1019..4bde0115655d 100644 --- a/src/Files.App/GlobalUsings.cs +++ b/src/Files.App/GlobalUsings.cs @@ -33,7 +33,6 @@ global using global::Files.App.Utils.Shell; global using global::Files.App.Utils.StatusCenter; global using global::Files.App.Utils.Storage; -global using global::Files.App.Utils.Taskbar; global using global::Files.App.Data.Behaviors; global using global::Files.App.Data.Commands; global using global::Files.App.Data.Contexts; @@ -75,11 +74,7 @@ // Files.Platform global using global::Files.Platform.Abstractions; -#if WINDOWS -global using global::Files.Platform.Windows; -#else global using global::Files.Platform.Linux; -#endif // Files.App.Storage @@ -92,7 +87,5 @@ global using global::Files.Shared.Attributes; global using global::Files.Shared.Extensions; -#if !WINDOWS // Uno declares ThumbnailMode in both Windows.Storage and Windows.Storage.FileProperties global using ThumbnailMode = global::Windows.Storage.FileProperties.ThumbnailMode; -#endif diff --git a/src/Files.App/Helpers/Application/AppLifecycleHelper.cs b/src/Files.App/Helpers/Application/AppLifecycleHelper.cs index 55e01bf58ffb..050449cf4d22 100644 --- a/src/Files.App/Helpers/Application/AppLifecycleHelper.cs +++ b/src/Files.App/Helpers/Application/AppLifecycleHelper.cs @@ -104,9 +104,6 @@ public static async Task InitializeAppComponentsAsync() var userSettingsService = Ioc.Default.GetRequiredService(); var addItemService = Ioc.Default.GetRequiredService(); var generalSettingsService = userSettingsService.GeneralSettingsService; -#if WINDOWS - var jumpListService = Ioc.Default.GetRequiredService(); -#endif ActiveSessionTracker.ReportPersistedTime(); @@ -119,17 +116,11 @@ await Task.WhenAll( App.LibraryManager.UpdateLibrariesAsync(), OptionalTaskAsync(WSLDistroManager.UpdateDrivesAsync(), generalSettingsService.ShowWslSection), OptionalTaskAsync(App.FileTagsManager.UpdateFileTagsAsync(), generalSettingsService.ShowFileTagsSection) -#if WINDOWS - , jumpListService.InitializeAsync() -#endif ); //Start the tasks separately to reduce resource contention await Task.WhenAll( addItemService.InitializeAsync() -#if WINDOWS - , ContextMenu.WarmUpQueryContextMenuAsync() -#endif ); }); @@ -324,13 +315,9 @@ public static IServiceProvider ConfigureHost(AppModel appModel) services // Platform services -#if WINDOWS - .AddWindowsPlatform() -#else .AddLinuxPlatform() .AddSingleton(_ => Program.SingleInstance ?? new Files.Platform.Linux.Instance.LinuxSingleInstanceService()) .AddLinuxSystemIntegration() -#endif // Settings services .AddSingleton() .AddSingleton(sp => new AppearanceSettingsService(((UserSettingsService)sp.GetRequiredService()).GetSharingContext())) @@ -354,26 +341,15 @@ public static IServiceProvider ConfigureHost(AppModel appModel) .AddSingleton() .AddSingleton() // Services -#if WINDOWS - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() -#else .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() -#endif .AddSingleton() .AddSingleton() -#if WINDOWS - .AddSingleton() -#else .AddSingleton() -#endif .AddSingleton() .AddSingleton() .AddSingleton() @@ -383,45 +359,20 @@ public static IServiceProvider ConfigureHost(AppModel appModel) .AddSingleton() .AddSingleton() .AddSingleton() -#if WINDOWS - .AddSingleton() -#else .AddSingleton() -#endif .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() -#if WINDOWS - .AddSingleton() -#else .AddSingleton() -#endif .AddSingleton() -#if WINDOWS - .AddSingleton() -#endif -#if WINDOWS - .AddSingleton() -#else .AddSingleton() -#endif .AddSingleton() .AddSingleton() -#if WINDOWS - .AddSingleton() -#else .AddSingleton() -#endif .AddSingleton() .AddSingleton() .AddSingleton() -#if WINDOWS - .AddSingleton() -#endif -#if WINDOWS - .AddSingleton() -#endif .AddSingleton() // ViewModels .AddSingleton() @@ -449,19 +400,10 @@ public static IServiceProvider ConfigureHost(AppModel appModel) // Storable path resolution services.AddStorables(); services.AddFtpStorables(); -#if !WINDOWS Files.App.Storage.Archives.ArchiveServiceCollectionExtensions.AddArchiveStorables(services); services.AddSingleton(); -#endif // Conditional DI -#if WINDOWS - if (AppEnvironment is AppEnvironment.SideloadPreview or AppEnvironment.SideloadStable) - services.AddSingleton(); - else if (AppEnvironment is AppEnvironment.StorePreview or AppEnvironment.StoreStable) - services.AddSingleton(); - else -#endif services.AddSingleton(); return services.BuildServiceProvider(); @@ -644,9 +586,6 @@ public static void HandleAppUnhandledException(Exception? ex, bool showToastNoti if (!showToastNotification) return; -#if WINDOWS - SafetyExtensions.IgnoreExceptions(AppToastNotificationHelper.ShowUnhandledExceptionToast); -#endif SafetyExtensions.IgnoreExceptions(() => { @@ -698,12 +637,6 @@ private static void GeneralSettingsService_PropertyChanged(object? sender, Prope if (e.PropertyName == nameof(IGeneralSettingsService.ShowSystemTrayIcon)) { -#if WINDOWS - if (generalSettingsService.ShowSystemTrayIcon) - App.SystemTrayIcon?.Show(); - else - App.SystemTrayIcon?.Hide(); -#endif } } } diff --git a/src/Files.App/Helpers/Application/AppMemoryHelper.cs b/src/Files.App/Helpers/Application/AppMemoryHelper.cs index 2c893652143e..f2b5d2590575 100644 --- a/src/Files.App/Helpers/Application/AppMemoryHelper.cs +++ b/src/Files.App/Helpers/Application/AppMemoryHelper.cs @@ -1,11 +1,6 @@ // Copyright (c) Files Community // SPDX-License-Identifier: MPL-2.0 -#if WINDOWS -#if WINDOWS -using Windows.Win32; -#endif -#endif namespace Files.App.Helpers { @@ -73,10 +68,6 @@ private static void EnsureWorker() if (Volatile.Read(ref trimRequested) == 0 && Environment.TickCount64 - Interlocked.Read(ref lastActivityTicks) >= QuietWindowMs) { -#if WINDOWS - using var process = Process.GetCurrentProcess(); - PInvoke.K32EmptyWorkingSet(new Windows.Win32.Foundation.HANDLE(process.Handle)); -#endif } } diff --git a/src/Files.App/Helpers/Application/AppToastNotificationHelper.cs b/src/Files.App/Helpers/Application/AppToastNotificationHelper.cs deleted file mode 100644 index 3bfb070c4e06..000000000000 --- a/src/Files.App/Helpers/Application/AppToastNotificationHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Microsoft.Windows.AppNotifications; -using Microsoft.Windows.AppNotifications.Builder; - -namespace Files.App.Helpers.Application -{ - internal static class AppToastNotificationHelper - { - public static void ShowUnhandledExceptionToast() - { - var toastContent = new AppNotificationBuilder() - .AddText(Strings.ExceptionNotificationHeader.GetLocalizedResource()) - .AddText(Strings.ExceptionNotificationBody.GetLocalizedResource()) - .SetAppLogoOverride(new Uri("ms-appx:///Assets/error.png")) - .AddButton(new AppNotificationButton(Strings.ExceptionNotificationReportButton.GetLocalizedResource()) - .SetInvokeUri(new Uri(Constants.ExternalUrl.BugReportUrl))) - .BuildNotification(); - AppNotificationManager.Default.Show(toastContent); - } - - public static void ShowBackgroundRunningToast() - { - var toastContent = new AppNotificationBuilder() - .AddText(Strings.BackgroundRunningNotificationHeader.GetLocalizedResource()) - .AddText(Strings.BackgroundRunningNotificationBody.GetLocalizedResource()) - .BuildNotification(); - AppNotificationManager.Default.Show(toastContent); - } - - public static void ShowDriveEjectToast() - { - var toastContent = new AppNotificationBuilder() - .AddText(Strings.EjectNotificationHeader.GetLocalizedResource()) - .AddText(Strings.EjectNotificationBody.GetLocalizedResource()) -#if WINDOWS - .SetAttributionText("Files") -#else - .SetAttributionText(Strings.LinuxAppDisplayName.GetLocalizedResource()) -#endif - .BuildNotification(); - AppNotificationManager.Default.Show(toastContent); - } - } -} diff --git a/src/Files.App/Helpers/Layout/LayoutPreferencesDatabase.Windows.cs b/src/Files.App/Helpers/Layout/LayoutPreferencesDatabase.Windows.cs deleted file mode 100644 index f8332e273a43..000000000000 --- a/src/Files.App/Helpers/Layout/LayoutPreferencesDatabase.Windows.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; -using System.Runtime.CompilerServices; -using Windows.ApplicationModel; -using static Files.App.Helpers.LayoutPreferencesDatabaseItemRegistry; -using static Files.App.Helpers.RegistryHelpers; -using JsonSerializer = System.Text.Json.JsonSerializer; - -namespace Files.App.Helpers -{ - public sealed class LayoutPreferencesDatabase - { - private readonly static string LayoutSettingsKey = @$"Software\Files Community\{Package.Current.Id.Name}\v1\LayoutPreferences"; - - public LayoutPreferencesItem? GetPreferences(string filePath, ulong? frn) - { - return FindPreferences(filePath, frn)?.LayoutPreferencesManager; - } - - public void SetPreferences(string filePath, ulong? frn, LayoutPreferencesItem? preferencesItem) - { - var tmp = FindPreferences(filePath, frn); - - if (tmp is null) - { - if (preferencesItem is not null) - { - // Insert new tagged file (Id will be auto-incremented) - var newPref = new LayoutPreferencesDatabaseItem() - { - FilePath = filePath, - Frn = frn, - LayoutPreferencesManager = preferencesItem - }; - - UpdateValues(newPref); - } - } - else - { - if (preferencesItem is not null) - { - // Update file tag - tmp.LayoutPreferencesManager = preferencesItem; - - UpdateValues(tmp); - } - else - { - // Remove file tag - UpdateValues(null); - } - } - - void UpdateValues(LayoutPreferencesDatabaseItem? preferences) - { - if (filePath is not null) - { - using var filePathKey = Registry.CurrentUser.CreateSubKey(CombineKeys(LayoutSettingsKey, filePath)); - SaveValues(filePathKey, preferences); - } - - if (frn is not null) - { - using var frnKey = Registry.CurrentUser.CreateSubKey(CombineKeys(LayoutSettingsKey, "FRN", frn.Value.ToString())); - SaveValues(frnKey, preferences); - } - } - } - - public void ResetAll() - { - Registry.CurrentUser.DeleteSubKeyTree(LayoutSettingsKey, false); - } - - public void Import(string json) - { - var preferences = JsonSerializer.Deserialize(json, AppJsonSerializerContext.Default.LayoutPreferencesDatabaseItemArray); - ImportCore(preferences); - } - - - private static void ImportCore(LayoutPreferencesDatabaseItem[]? preferences) - { - Registry.CurrentUser.DeleteSubKeyTree(LayoutSettingsKey, false); - if (preferences is null) - { - return; - } - foreach (var preference in preferences) - { - using var filePathKey = Registry.CurrentUser.CreateSubKey(CombineKeys(LayoutSettingsKey, preference.FilePath)); - SaveValues(filePathKey, preference); - if (preference.Frn is not null) - { - using var frnKey = Registry.CurrentUser.CreateSubKey(CombineKeys(LayoutSettingsKey, "FRN", preference.Frn.Value.ToString())); - SaveValues(frnKey, preference); - } - } - } - - public string Export() - { - var list = new List(); - IterateKeys(list, LayoutSettingsKey, 0); - return JsonSerializer.Serialize(list, AppJsonSerializerContext.Default.ListLayoutPreferencesDatabaseItem); - } - - private void IterateKeys(List list, string path, int depth) - { - using var key = Registry.CurrentUser.OpenSubKey(path); - if (key is null) - { - return; - } - - if (key.ValueCount > 0) - { - var preference = new LayoutPreferencesDatabaseItem(); - BindValues(key, preference); - list.Add(preference); - } - - foreach (var subKey in key.GetSubKeyNames()) - { - if (depth == 0 && subKey == "FRN") - { - // Skip FRN key - continue; - } - - IterateKeys(list, CombineKeys(path, subKey), depth + 1); - } - } - - private LayoutPreferencesDatabaseItem? FindPreferences(string filePath, ulong? frn) - { - if (filePath is not null) - { - using var filePathKey = Registry.CurrentUser.OpenSubKey(CombineKeys(LayoutSettingsKey, filePath), writable: true); - if (filePathKey is not null && filePathKey.ValueCount > 0) - { - var preference = new LayoutPreferencesDatabaseItem(); - BindValues(filePathKey, preference); - if (frn is not null && preference.Frn != frn) - { - // Keep entry updated - preference.Frn = frn; - var value = frn.Value; - filePathKey.SetValue(nameof(LayoutPreferencesDatabaseItem.Frn), Unsafe.As(ref value), RegistryValueKind.QWord); - } - return preference; - } - } - - if (frn is not null) - { - using var frnKey = Registry.CurrentUser.OpenSubKey(CombineKeys(LayoutSettingsKey, "FRN", frn.Value.ToString()), writable: true); - if (frnKey is not null && frnKey.ValueCount > 0) - { - var preference = new LayoutPreferencesDatabaseItem(); - BindValues(frnKey, preference); - if (filePath is not null && preference.FilePath != filePath) - { - // Keep entry updated - preference.FilePath = filePath; - frnKey.SetValue(nameof(LayoutPreferencesDatabaseItem.FilePath), filePath, RegistryValueKind.String); - } - return preference; - } - } - - return null; - } - } -} diff --git a/src/Files.App/Helpers/Layout/LayoutPreferencesManager.cs b/src/Files.App/Helpers/Layout/LayoutPreferencesManager.cs index 9fd9193e6c17..fc4578364aef 100644 --- a/src/Files.App/Helpers/Layout/LayoutPreferencesManager.cs +++ b/src/Files.App/Helpers/Layout/LayoutPreferencesManager.cs @@ -1,9 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if WINDOWS -using Windows.Win32; -#endif namespace Files.App.Helpers { @@ -579,34 +576,13 @@ public static void SetLayoutPreferencesForPath(string? path, LayoutPreferencesIt // The Windows file reference number; on Linux the layout database tracks folders by dev:ino itself (IFileStatService). private static ulong? GetFolderFRN(string? path) { -#if WINDOWS - return Win32Helper.GetFolderFRN(path); -#else return null; -#endif } private static LayoutPreferencesItem? GetLayoutPreferencesFromAds(string path, ulong? frn) { -#if WINDOWS - var str = Win32Helper.ReadStringFromFile($"{path}:files_layoutmode"); - - var layoutPreferences = SafetyExtensions.IgnoreExceptions(() => string.IsNullOrEmpty(str) - ? null - : JsonSerializer.Deserialize(str, AppJsonSerializerContext.Default.LayoutPreferencesItem)); - - if (layoutPreferences is null) - return null; - - // Port settings to the database, delete the ADS - if (SetLayoutPreferencesToDatabase(path, frn, layoutPreferences)) - PInvoke.DeleteFileFromApp($"{path}:files_layoutmode"); - - return layoutPreferences; -#else // Alternate data streams do not exist on Linux return null; -#endif } private static LayoutPreferencesItem? GetLayoutPreferencesFromDatabase(string path, ulong? frn) @@ -625,9 +601,7 @@ public static void SetLayoutPreferencesForPath(string? path, LayoutPreferencesIt return new(); if (path == Constants.UserEnvironmentPaths.DownloadsPath -#if !WINDOWS && Files.App.UnoVirtualization.VirtualizingWrapGrid.IsSupported(out _) -#endif ) { // Default for downloads folder is to group by date created diff --git a/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs b/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs index 501c9ada6432..f75cc6d7776a 100644 --- a/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs +++ b/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs @@ -14,10 +14,8 @@ public static class LayoutSizeKindHelper /// public static uint GetIconSize(FolderLayoutModes folderLayoutMode) { -#if !WINDOWS if (folderLayoutMode == FolderLayoutModes.GridView) return (uint)Math.Max(1, GetGridViewItemWidth(LayoutSettingsService.GridViewSize) - 24); -#endif return folderLayoutMode switch { // Details diff --git a/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs b/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs index 4a7ded659fef..6bd26e752999 100644 --- a/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs +++ b/src/Files.App/Helpers/MenuFlyout/FastContextFlyout.cs @@ -29,10 +29,8 @@ public sealed class FastContextFlyout private bool openedUp; private bool placementResolved; private double estimatedWidth; -#if !WINDOWS private double invocationScreenY = double.NaN; private bool preserveOpenPlacement; -#endif private FrameworkElement? invocationAnchor; private Point? invocationPosition; private readonly Stopwatch openStopwatch = new(); @@ -57,9 +55,7 @@ public FastContextFlyout() App.LastOpenedFlyout = Flyout; openStopwatch.Restart(); }; -#if !WINDOWS Flyout.Closing += Flyout_Closing; -#endif Flyout.Opened += (s, e) => openStopwatch.Restart(); Flyout.Opened += Flyout_Opened; Flyout.Closed += Flyout_Closed; @@ -70,10 +66,8 @@ public FastContextFlyout() /// public void Reset() { -#if !WINDOWS invocationScreenY = double.NaN; preserveOpenPlacement = false; -#endif Flyout.Items.Clear(); primaryRow = null; primarySeparator = null; @@ -92,17 +86,13 @@ public void Reset() /// public void Build(List models, bool preservePlacement = false) { -#if !WINDOWS var savedPlacement = (invocationAnchor, invocationPosition, invocationScreenY, openedUp, placementResolved); -#endif Reset(); -#if !WINDOWS if (preservePlacement) { (invocationAnchor, invocationPosition, invocationScreenY, openedUp, placementResolved) = savedPlacement; preserveOpenPlacement = !double.IsNaN(invocationScreenY); } -#endif var primary = models.Where(x => x.IsPrimary && !x.IsHidden && x.ShowItem).ToList(); var secondary = models @@ -379,7 +369,6 @@ void Revert() /// public void ResolvePlacement(FrameworkElement? anchor = null, Point? position = null) { -#if !WINDOWS if (preserveOpenPlacement) { placementResolved = true; @@ -387,7 +376,6 @@ public void ResolvePlacement(FrameworkElement? anchor = null, Point? position = CorrectRebuiltPlacement(); return; } -#endif invocationAnchor = anchor; invocationPosition = position; openedUp = PredictOpensUpward(); @@ -527,12 +515,10 @@ async Task PopulateAsync() return subMenu; } -#if !WINDOWS public void CorrectRebuiltPlacement() { Flyout_Opened(Flyout, EventArgs.Empty); } -#endif [DynamicWindowsRuntimeCast(typeof(MenuFlyoutPresenter))] [DynamicWindowsRuntimeCast(typeof(FrameworkElement))] @@ -577,9 +563,7 @@ private void Flyout_Opened(object? sender, object e) // Pull the touch/pointer point captured after the pre-render guess; the cursor is stale for touch. // Direct-position callers (widget/sidebar) leave the provider null. if ( -#if !WINDOWS !preserveOpenPlacement && -#endif InvocationPointProvider?.Invoke() is { } invocation) { invocationAnchor = invocation.Anchor; @@ -593,15 +577,11 @@ private void Flyout_Opened(object? sender, object e) // from the popup window's screen position; in-window popups fall back to the offset. The row goes // on whichever end is nearest the invocation point - also the best answer when the menu is taller // than the work area and the pointer lands mid-menu. -#if WINDOWS - var referenceScreenY = GetInvocationReferenceScreenY(); -#else if (!preserveOpenPlacement || double.IsNaN(invocationScreenY)) invocationScreenY = GetInvocationReferenceScreenY(); var referenceScreenY = invocationScreenY; preserveOpenPlacement = true; placementResolved = true; -#endif if (!double.IsNaN(referenceScreenY) && presenter.ActualHeight > 0) { var popupScale = presenter.XamlRoot.RasterizationScale; diff --git a/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs b/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs index 158a7640f1be..6d5543cf42ee 100644 --- a/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs +++ b/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Icons; using Files.Platform.Abstractions.Mime; using Files.Platform.Linux.Icons; @@ -61,4 +60,3 @@ internal static class LinuxAppIcons } } } -#endif diff --git a/src/Files.App/Helpers/Navigation/ArchiveOpenTempStore.Linux.cs b/src/Files.App/Helpers/Navigation/ArchiveOpenTempStore.Linux.cs index 6377257d2db4..df48a2f22b97 100644 --- a/src/Files.App/Helpers/Navigation/ArchiveOpenTempStore.Linux.cs +++ b/src/Files.App/Helpers/Navigation/ArchiveOpenTempStore.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using System.IO; using System.Text; @@ -169,4 +168,3 @@ private static void TryDelete(string? directory) } } } -#endif diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.Linux.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.Linux.cs index c6d09900501e..83bb7bd1fd07 100644 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.Linux.cs +++ b/src/Files.App/Helpers/Navigation/NavigationHelpers.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.App.Dialogs; using Files.Platform.Abstractions.Archives; using Files.Platform.Abstractions.Launching; @@ -473,4 +472,3 @@ private static bool IsInApplicationsDirectory(string path) } } } -#endif diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.Windows.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.Windows.cs deleted file mode 100644 index 27b2307e9047..000000000000 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.Windows.cs +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Media.Imaging; -using System.IO; -using Windows.Storage; -using Windows.Storage.Search; -using Windows.System; -using WinRT; -using Windows.Win32; - -namespace Files.App.Helpers -{ - public static partial class NavigationHelpers - { - private static readonly IWindowsRecentItemsService WindowsRecentItemsService = Ioc.Default.GetRequiredService(); - - private static async Task OpenPathWindowsAsync(string path, IShellPage associatedInstance, FilesystemItemType? itemType, bool openSilent, bool openViaApplicationPicker, IEnumerable? selectItems, string? args, bool forceOpenInNewTab) - { - string? previousDir = associatedInstance.ShellViewModel.WorkingDirectory; - - var fileAttributes = Win32Helper.GetFileAttributes(path); - bool isDirectory = fileAttributes.HasFlag(System.IO.FileAttributes.Directory); - - var shortcutInfo = new ShellLinkItem(); - - if (!isDirectory && FileExtensionHelpers.IsShortcutOrUrlFile(path)) - { - var shInfo = await FileOperationsHelpers.ParseLinkAsync(path); - - if (shInfo is null) - return false; - - itemType = shInfo.IsFolder ? FilesystemItemType.Directory : FilesystemItemType.File; - - shortcutInfo = shInfo; - - if (shortcutInfo.InvalidTarget) - { - if (await DialogDisplayHelper.ShowDialogAsync(DynamicDialogFactory.GetFor_ShortcutNotFound(shortcutInfo.TargetPath)) != DynamicDialogResult.Primary) - return false; - - // Delete shortcut - var shortcutItem = StorageHelpers.FromPathAndType(path, FilesystemItemType.File); - await associatedInstance.FilesystemHelpers.DeleteItemAsync(shortcutItem, DeleteConfirmationPolicies.Never, false, true); - } - } - else if (fileAttributes.HasFlag(System.IO.FileAttributes.ReparsePoint)) - { - if (!isDirectory && - Win32Helper.GetWin32FindDataForPath(path, out var findData) && - findData.dwReserved0 == PInvoke.IO_REPARSE_TAG_SYMLINK) - { - shortcutInfo.TargetPath = Win32Helper.ParseSymLink(path); - } - itemType ??= isDirectory ? FilesystemItemType.Directory : FilesystemItemType.File; - } - else if (fileAttributes.HasFlag(System.IO.FileAttributes.Hidden)) - { - itemType = isDirectory ? FilesystemItemType.Directory : FilesystemItemType.File; - } - else if (itemType is null) - { - itemType = await StorageHelpers.GetTypeFromPath(path); - } - - FilesystemResult opened = (FilesystemResult)false; - switch (itemType) - { - case FilesystemItemType.Library: - opened = await OpenLibrary(path, associatedInstance, selectItems, forceOpenInNewTab); - break; - - case FilesystemItemType.Directory: - opened = await OpenDirectory(path, associatedInstance, selectItems, shortcutInfo, forceOpenInNewTab, fileAttributes.HasFlag(System.IO.FileAttributes.Hidden)); - break; - - case FilesystemItemType.File: - // Starts the screensaver in full-screen mode - if (FileExtensionHelpers.IsScreenSaverFile(path)) - args += "/s"; - - opened = await OpenFile(path, associatedInstance, shortcutInfo, openViaApplicationPicker, args); - break; - } - - if (opened.ErrorCode == FileSystemStatusCode.NotFound && !openSilent) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - associatedInstance.ToolbarViewModel.CanRefresh = false; - associatedInstance.ShellViewModel?.RefreshItems(previousDir); - } - - return opened; - } - - private static async Task OpenLibrary(string path, IShellPage associatedInstance, IEnumerable? selectItems, bool forceOpenInNewTab) - { - IUserSettingsService UserSettingsService = Ioc.Default.GetRequiredService(); - - var opened = (FilesystemResult)false; - bool isHiddenItem = Win32Helper.HasFileAttribute(path, System.IO.FileAttributes.Hidden); - if (isHiddenItem) - { - await OpenPath(forceOpenInNewTab, UserSettingsService.FoldersSettingsService.OpenFoldersInNewTab, path, associatedInstance); - opened = (FilesystemResult)true; - } - else if (App.LibraryManager.TryGetLibrary(path, out var library)) - { - opened = (FilesystemResult)await library.CheckDefaultSaveFolderAccess(); - if (opened) - await OpenPathAsync(forceOpenInNewTab, UserSettingsService.FoldersSettingsService.OpenFoldersInNewTab, path, library.Text, associatedInstance, selectItems); - } - return opened; - } - - private static async Task OpenDirectory(string path, IShellPage associatedInstance, IEnumerable? selectItems, ShellLinkItem shortcutInfo, bool forceOpenInNewTab, bool isHiddenItem) - { - IUserSettingsService UserSettingsService = Ioc.Default.GetRequiredService(); - - var opened = (FilesystemResult)false; - bool isShortcut = FileExtensionHelpers.IsShortcutOrUrlFile(path); - - if (isShortcut) - { - if (string.IsNullOrEmpty(shortcutInfo.TargetPath)) - { - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance); - opened = (FilesystemResult)true; - } - else - { - await OpenPath(forceOpenInNewTab, UserSettingsService.FoldersSettingsService.OpenFoldersInNewTab, shortcutInfo.TargetPath, associatedInstance, selectItems); - opened = (FilesystemResult)true; - } - } - else if (isHiddenItem) - { - await OpenPath(forceOpenInNewTab, UserSettingsService.FoldersSettingsService.OpenFoldersInNewTab, path, associatedInstance); - opened = (FilesystemResult)true; - } - else - { - if (associatedInstance.ShellViewModel is not null) - { - opened = await associatedInstance.ShellViewModel.GetFolderWithPathFromPathAsync(path) - .OnSuccess(async (childFolder) => - { - var folder = childFolder!; - // Add location to Recent Items List. - // File.Exists distinguishes an archive root (real file on disk) from an inner path like "archive.zip\sub". - await STATask.RunPooled(() => - { - if (folder.Item is SystemStorageFolder || - (folder.Item is ZipStorageFolder && File.Exists(folder.Path))) - return WindowsRecentItemsService.Add(folder.Path); - - return false; - }, App.Logger); - }); - } - if (!opened) - opened = (FilesystemResult)await Task.Run(() => FolderHelpers.CheckFolderAccessWithWin32(path)); - - if (opened) - await OpenPath(forceOpenInNewTab, UserSettingsService.FoldersSettingsService.OpenFoldersInNewTab, path, associatedInstance, selectItems); - else - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance); - } - return opened; - } - - private static async Task OpenFile(string path, IShellPage associatedInstance, ShellLinkItem shortcutInfo, bool openViaApplicationPicker = false, string? args = default) - { - var opened = (FilesystemResult)false; - bool isHiddenItem = Win32Helper.HasFileAttribute(path, System.IO.FileAttributes.Hidden); - bool isShortcut = FileExtensionHelpers.IsShortcutOrUrlFile(path) || !string.IsNullOrEmpty(shortcutInfo.TargetPath); - - if (isShortcut) - { - // Empty or non-rooted shell target (e.g. a shell:appsfolder app): launch the .lnk so the shell activates it - if (string.IsNullOrEmpty(shortcutInfo.TargetPath) || !Path.IsPathRooted(shortcutInfo.TargetPath)) - { - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args); - } - else - { - if (!FileExtensionHelpers.IsWebLinkFile(path) && associatedInstance.ShellViewModel is not null) - { - var childFileResult = await associatedInstance.ShellViewModel.GetFileWithPathFromPathAsync(shortcutInfo.TargetPath); - // Add location to Recent Items List - if (childFileResult.Result is { Item: SystemStorageFile } childFile) - WindowsRecentItemsService.Add(childFile.Path); - } - await Win32Helper.InvokeWin32ComponentAsync(shortcutInfo.TargetPath, associatedInstance, $"{args} {shortcutInfo.Arguments}", shortcutInfo.RunAsAdmin, shortcutInfo.WorkingDirectory); - } - opened = (FilesystemResult)true; - } - else if (isHiddenItem) - { - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args); - } - else - { - if (associatedInstance.ShellViewModel is not null) - { - var shellViewModel = associatedInstance.ShellViewModel; - - opened = await shellViewModel.GetFileWithPathFromPathAsync(path) - .OnSuccess(async childFile => - { - var file = childFile!; - // Add location to Recent Items List - if (file.Item is SystemStorageFile) - WindowsRecentItemsService.Add(file.Path); - - if (openViaApplicationPicker) - { - var storageFile = file.Item - ?? throw new InvalidOperationException("The file cannot be opened with the application picker because it has no storage item."); - - LauncherOptions options = InitializeWithWindow(new LauncherOptions - { - DisplayApplicationPicker = true - }); - if (!await Launcher.LaunchFileAsync(storageFile, options)) - await ContextMenu.InvokeVerb("openas", path); - } - else - { - var fileExtension = Path.GetExtension(path); - - // Use NeighboringFilesQuery to launch photos - // The query options no longer work with the Windows 11 Photo App but they still work for Windows 10 - if (FileExtensionHelpers.IsImageFile(fileExtension)) - { - //try using launcher first - bool launchSuccess = false; - - // The Windows 11 Photos app ignores NeighboringFilesQuery when launched as default app. - // Use the app URI only when this extension is associated with Microsoft Photos. - if (FileAssociationHelpers.IsMicrosoftPhotosDefaultAssociation(fileExtension)) - { - string uri = $"ms-photos:viewer?fileName={Uri.EscapeDataString(path)}"; - launchSuccess = await Launcher.LaunchUriAsync(new Uri(uri)); - } - - BaseStorageFileQueryResult? fileQueryResult = null; - //Get folder to create a file query (to pass to apps like Photos, Movies & TV..., needed to scroll through the folder like what Windows Explorer does) - var currentFolderResult = await shellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(path)); - if (!launchSuccess && currentFolderResult.Result is { } currentFolder) - { - QueryOptions queryOptions = new(CommonFileQuery.DefaultQuery, null); - //We can have many sort entries - SortEntry sortEntry = new() - { - AscendingOrder = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortDirection == SortDirection.Ascending - }; - //Basically we tell to the launched app to follow how we sorted the files in the directory. - var sortOption = associatedInstance.InstanceViewModel.FolderSettings.DirectorySortOption; - switch (sortOption) - { - case SortOption.Name: - sortEntry.PropertyName = "System.ItemNameDisplay"; - queryOptions.SortOrder.Clear(); - queryOptions.SortOrder.Add(sortEntry); - break; - case SortOption.DateModified: - sortEntry.PropertyName = "System.DateModified"; - queryOptions.SortOrder.Clear(); - queryOptions.SortOrder.Add(sortEntry); - break; - case SortOption.DateCreated: - sortEntry.PropertyName = "System.DateCreated"; - queryOptions.SortOrder.Clear(); - queryOptions.SortOrder.Add(sortEntry); - break; - //Unfortunately this is unsupported | Remarks: https://learn.microsoft.com/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041 - //case Enums.SortOption.Size: - //sortEntry.PropertyName = "System.TotalFileSize"; - //queryOptions.SortOrder.Clear(); - //queryOptions.SortOrder.Add(sortEntry); - //break; - //Unfortunately this is unsupported | Remarks: https://learn.microsoft.com/uwp/api/windows.storage.search.queryoptions.sortorder?view=winrt-19041 - //case Enums.SortOption.FileType: - //sortEntry.PropertyName = "System.FileExtension"; - //queryOptions.SortOrder.Clear(); - //queryOptions.SortOrder.Add(sortEntry); - //break; - //Handle unsupported - default: - //keep the default one in SortOrder IList - break; - } - var options = InitializeWithWindow(new LauncherOptions()); - if (currentFolder.AreQueryOptionsSupported(queryOptions)) - { - fileQueryResult = currentFolder.CreateFileQueryWithOptions(queryOptions); - options.NeighboringFilesQuery = fileQueryResult.ToStorageFileQueryResult(); - } - // Now launch file with options. - if (file.Item is { } item && - (await FilesystemTasks.Wrap(() => item.ToStorageFileAsync().AsTask())).Result is { } storageItem) - { - launchSuccess = await Launcher.LaunchFileAsync(storageItem, options); - } - } - if (!launchSuccess) - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args); - } - else if (file.Item is ZipStorageFile zipStorageFile) - { - var options = InitializeWithWindow(new LauncherOptions()); - var storageItem = (await FilesystemTasks.Wrap(() => zipStorageFile.ToStorageFileAsync().AsTask())).Result; - if (storageItem is null) - { - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args); - } - else if (!await Launcher.LaunchFileAsync(storageItem, options)) - { - var pickerOptions = InitializeWithWindow(new LauncherOptions - { - DisplayApplicationPicker = true - }); - if (!await Launcher.LaunchFileAsync(storageItem, pickerOptions)) - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args); - } - } - else - { - await Win32Helper.InvokeWin32ComponentAsync(path, associatedInstance, args); - } - } - }); - } - } - return opened; - } - - private static LauncherOptions InitializeWithWindow(LauncherOptions obj) - { - WinRT.Interop.InitializeWithWindow.Initialize(obj, MainWindow.Instance.WindowHandle); - return obj; - } - } -} diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs index 53cb52a4e058..cb42f0e63189 100644 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs +++ b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs @@ -188,10 +188,8 @@ internal static void RefreshTabPathHints() } } } -#if !WINDOWS foreach (var tab in MainPageViewModel.AppInstances.Where(tab => !string.IsNullOrEmpty(tab.Header))) tab.Header = MainWindow.FormatRootModeTitle(tab.Header!); -#endif } private static string[] AncestorHints(string? path) @@ -389,10 +387,8 @@ await SafetyExtensions.IgnoreExceptions(async () => if (isCurrent) { var title = $"{windowTitle} - {(OperatingSystem.IsLinux() ? Strings.LinuxAppDisplayName.GetLocalizedResource() : "Files")}"; -#if !WINDOWS title = Files.Platform.Linux.Windowing.X11WindowChrome.SanitizeTitle(MainWindow.FormatRootModeTitle(title)); MainWindow.Instance.UpdateLinuxWindowTitle(title); -#endif MainWindow.Instance.AppWindow.Title = title; } }); @@ -446,10 +442,8 @@ private static Task LaunchNewLinuxInstance() startInfo.Environment["FILES_NO_SINGLE_INSTANCE"] = "1"; startInfo.ArgumentList.Add("--new-window"); -#if !WINDOWS if (Files.Platform.Linux.Elevation.RootActionMode.IsRequested(Program.LaunchArguments)) startInfo.ArgumentList.Add("--root"); -#endif System.Diagnostics.Process.Start(startInfo)?.Dispose(); } catch (Exception ex) @@ -501,17 +495,11 @@ public static async Task OpenSelectedItemsAsync(IShellPage associatedInstance, b if (!openViaApplicationPicker && selectedItems.Count > 1 && selectedItems.All(x => x.PrimaryItemAttribute == StorageItemTypes.File && !x.IsExecutable && !x.IsShortcut) -#if !WINDOWS && selectedItems.All(x => !FileExtensionHelpers.IsZipPath(x.GetRequiredPath()) && !Ioc.Default.GetRequiredService().IsArchiveFileName(x.GetRequiredPath())) -#endif ) { -#if !WINDOWS opened = await OpenFilesLinuxAsync(selectedItems.Select(x => x.GetRequiredPath())); -#else - opened = await Win32Helper.InvokeWin32ComponentAsync(string.Join('|', selectedItems.Select(x => x.ItemPath)), associatedInstance); -#endif } if (opened) @@ -527,9 +515,7 @@ public static async Task OpenSelectedItemsAsync(IShellPage associatedInstance, b await OpenPath(itemPath, associatedInstance, type, false, openViaApplicationPicker, forceOpenInNewTab: forceOpenInNewTab); if (type == FilesystemItemType.Directory -#if !WINDOWS || (!openViaApplicationPicker && Ioc.Default.GetRequiredService().IsArchiveFileName(itemPath)) -#endif ) forceOpenInNewTab = true; } @@ -548,12 +534,7 @@ public static async Task OpenItemsWithExecutableAsync(IShellPage associatedInsta if (workingDirectory.StartsWith(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.Ordinal)) return; -#if WINDOWS - var arguments = string.Join(" ", items.Select(item => $"\"{item.Path}\"")); - await Win32Helper.InvokeWin32ComponentAsync(executablePath, associatedInstance, arguments); -#else await RunWithItemsLinuxAsync(executablePath, items.Select(item => item.Path).ToArray()); -#endif } /// @@ -592,11 +573,7 @@ public static async Task OpenPath(string path, IShellPage associatedInstan return true; } -#if !WINDOWS return await OpenPathLinuxAsync(path, associatedInstance, openViaApplicationPicker, selectItems, forceOpenInNewTab); -#else - return await OpenPathWindowsAsync(path, associatedInstance, itemType, openSilent, openViaApplicationPicker, selectItems, args, forceOpenInNewTab); -#endif } diff --git a/src/Files.App/Helpers/ResourceLookup.cs b/src/Files.App/Helpers/ResourceLookup.cs index 74a6a3c5c342..2b85d423565f 100644 --- a/src/Files.App/Helpers/ResourceLookup.cs +++ b/src/Files.App/Helpers/ResourceLookup.cs @@ -1,11 +1,7 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if WINDOWS -using Microsoft.Windows.ApplicationModel.Resources; -#else using Windows.ApplicationModel.Resources; -#endif namespace Files.App.Helpers { @@ -14,20 +10,6 @@ namespace Files.App.Helpers /// internal static class ResourceLookup { -#if WINDOWS - private static readonly ResourceManager _manager = new(); - private static readonly ResourceMap? _tree = _manager.MainResourceMap.TryGetSubtree("Resources"); - private static ResourceContext? _context; - - public static string? TryGet(string key) - { - _context ??= _manager.CreateResourceContext(); - return _tree?.TryGetValue(key, _context)?.ValueAsString; - } - - /// Drops the cached context so a changed language override is picked up. - public static void Reset() => _context = null; -#else private static readonly ResourceLoader _loader = ResourceLoader.GetForViewIndependentUse(); public static string? TryGet(string key) @@ -37,6 +19,5 @@ internal static class ResourceLookup } public static void Reset() { } -#endif } } diff --git a/src/Files.App/Helpers/ShareItemHelpers.Windows.cs b/src/Files.App/Helpers/ShareItemHelpers.Windows.cs deleted file mode 100644 index 5d4ef13f04c3..000000000000 --- a/src/Files.App/Helpers/ShareItemHelpers.Windows.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.UI.Xaml.Controls; -using Windows.ApplicationModel.DataTransfer; -using Windows.Foundation.Metadata; -using Windows.Storage; - -namespace Files.App.Helpers -{ - public static partial class ShareItemHelpers - { - public static async Task ShareItemsAsync(IEnumerable itemsToShare) - { - if (itemsToShare is null) - return; - - var interop = DataTransferManager.As(); - IntPtr result = interop.GetForWindow(MainWindow.Instance.WindowHandle, Win32PInvoke.DataTransferManagerInteropIID); - - var manager = WinRT.MarshalInterface.FromAbi(result); - manager.DataRequested += Manager_DataRequested; - - try - { - interop.ShowShareUIForWindow(MainWindow.Instance.WindowHandle); - } - catch (Exception ex) - { - manager.DataRequested -= Manager_DataRequested; - - var errorDialog = new ContentDialog() - { - Title = Strings.FaildToShareItems.GetLocalizedResource(), - Content = ex.Message, - PrimaryButtonText = Strings.OK.GetLocalizedResource(), - }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - errorDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - await errorDialog.TryShowAsync(); - } - - async void Manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) - { - sender.DataRequested -= Manager_DataRequested; - - DataRequestDeferral dataRequestDeferral = args.Request.GetDeferral(); - List items = []; - DataRequest dataRequest = args.Request; - - foreach (ListedItem item in itemsToShare) - { - if (item is IShortcutItem shItem) - { - if (shItem.IsLinkItem && !string.IsNullOrEmpty(shItem.TargetPath)) - { - dataRequest.Data.Properties.Title = string.Format(Strings.ShareDialogTitle.GetLocalizedResource(), item.Name); - dataRequest.Data.Properties.Description = Strings.ShareDialogSingleItemDescription.GetLocalizedResource(); - dataRequest.Data.SetWebLink(new Uri(shItem.TargetPath)); - dataRequestDeferral.Complete(); - - return; - } - } - else if (item.PrimaryItemAttribute == StorageItemTypes.Folder && !item.IsArchive) - { - if (await StorageHelpers.ToStorageItem(item.ItemPath!) is BaseStorageFolder folder) - items.Add(folder); - } - else - { - if (await StorageHelpers.ToStorageItem(item.ItemPath!) is BaseStorageFile file) - items.Add(file); - } - } - - if (items.Count == 1) - { - dataRequest.Data.Properties.Title = string.Format(Strings.ShareDialogTitle.GetLocalizedResource(), items.First().Name); - dataRequest.Data.Properties.Description = Strings.ShareDialogSingleItemDescription.GetLocalizedResource(); - } - else if (items.Count == 0) - { - dataRequest.FailWithDisplayText(Strings.ShareDialogFailMessage.GetLocalizedResource()); - dataRequestDeferral.Complete(); - - return; - } - else - { - dataRequest.Data.Properties.Title = string.Format( - Strings.ShareDialogTitleMultipleItems.GetLocalizedResource(), - items.Count, - "ItemsCount.Text".GetLocalizedResource()); - dataRequest.Data.Properties.Description = Strings.ShareDialogMultipleItemsDescription.GetLocalizedResource(); - } - - dataRequest.Data.SetStorageItems(items, false); - dataRequestDeferral.Complete(); - } - } - } -} diff --git a/src/Files.App/Helpers/ShareItemHelpers.cs b/src/Files.App/Helpers/ShareItemHelpers.cs index 2cb46e8ff38b..acec4c997b9a 100644 --- a/src/Files.App/Helpers/ShareItemHelpers.cs +++ b/src/Files.App/Helpers/ShareItemHelpers.cs @@ -16,15 +16,9 @@ public static bool IsItemShareable(ListedItem item) (item.PrimaryItemAttribute != StorageItemTypes.Folder || item.IsArchive); public static bool IsSupported() -#if WINDOWS - => DataTransferManager.IsSupported(); -#else => false; // LINUX-TODO(share): Share UI is hidden on Linux; future work is an xdg-desktop-portal backend behind Files.Platform.Abstractions -#endif -#if !WINDOWS public static Task ShareItemsAsync(IEnumerable itemsToShare) => Task.CompletedTask; // LINUX-TODO(share): see IsSupported -#endif } } diff --git a/src/Files.App/Helpers/TransferHelpers.Windows.cs b/src/Files.App/Helpers/TransferHelpers.Windows.cs deleted file mode 100644 index e3550da46afa..000000000000 --- a/src/Files.App/Helpers/TransferHelpers.Windows.cs +++ /dev/null @@ -1,206 +0,0 @@ -using Microsoft.Extensions.Logging; -using System.Collections.Concurrent; -using Windows.ApplicationModel.DataTransfer; -using Windows.Storage; -using WinRT; - -namespace Files.App.Helpers -{ - public static partial class TransferHelpers - { - [DynamicWindowsRuntimeCast(typeof(StorageFile))] - [DynamicWindowsRuntimeCast(typeof(StorageFolder))] - public static async Task ExecuteTransferAsync(IReadOnlyList itemsToTransfer, ShellViewModel shellViewModel, StatusCenterViewModel statusViewModel, DataPackageOperation type = DataPackageOperation.Copy) - { - if (OperatingSystem.IsLinux()) - { - // LINUX-TODO(clipboard): W-CLIP replaces the in-app FileClipboard with the system clipboard - FileClipboard.Set(itemsToTransfer.Select(x => x.Id), type); - return; - } - - ConcurrentBag items = []; - var itemsCount = itemsToTransfer.Count; - var statusCenterItem = itemsCount > 50 ? StatusCenterHelper.AddCard_Prepare() : null; - var dataPackage = new DataPackage() { RequestedOperation = type }; - - try - { - // Update the status to in-progress - if (statusCenterItem is not null) - { - statusCenterItem.Progress.EnumerationCompleted = true; - statusCenterItem.Progress.ItemsCount = items.Count; - statusCenterItem.Progress.ReportStatus(FileSystemStatusCode.InProgress); - } - - await itemsToTransfer.ParallelForEachAsync(async storable => - { - // Update the status to increase processed count by one - if (statusCenterItem is not null) - { - statusCenterItem.Progress.AddProcessedItemsCount(1); - statusCenterItem.Progress.Report(); - } - - var result = storable switch - { - IFile => await shellViewModel.GetFileFromPathAsync(storable.Id).OnSuccess(x => items.Add(x - ?? throw new InvalidOperationException($"The file '{storable.Id}' could not be opened."))), - IFolder => await shellViewModel.GetFolderFromPathAsync(storable.Id).OnSuccess(x => items.Add(x - ?? throw new InvalidOperationException($"The folder '{storable.Id}' could not be opened."))), - _ => throw new ArgumentOutOfRangeException(nameof(storable)), - }; - - if (!result) - throw new SystemIO.IOException($"Failed to process {storable.Id} in cutting/copying to the clipboard.", (int)result.ErrorCode); - }, 10, statusCenterItem?.CancellationToken ?? CancellationToken.None); - - var standardObjectsOnly = items.All(x => x is StorageFile or StorageFolder or SystemStorageFile or SystemStorageFolder); - if (standardObjectsOnly) - items = new(await items.ToStandardStorageItemsAsync()); - - if (items.IsEmpty) - return; - - dataPackage.Properties.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; - dataPackage.SetStorageItems(items, false); - - Clipboard.SetContent(dataPackage); - } - catch (Exception ex) - { - if (ex is not SystemIO.IOException) - App.Logger.LogWarning(ex, "Failed to process cutting/copying due to an unknown error."); - - if ((FileSystemStatusCode)ex.HResult is FileSystemStatusCode.Unauthorized) - { - var filePaths = itemsToTransfer.Select(x => x.Id).ToArray(); - await FileOperationsHelpers.SetClipboard(filePaths, type); - } - } - finally - { - if (statusCenterItem is not null) - statusViewModel.RemoveItem(statusCenterItem); - } - } - - [DynamicWindowsRuntimeCast(typeof(StorageFile))] - [DynamicWindowsRuntimeCast(typeof(StorageFolder))] - public static async Task ExecuteTransferAsync(IContentPageContext context, StatusCenterViewModel statusViewModel, DataPackageOperation type = DataPackageOperation.Copy) - { - if (context.ShellPage?.SlimContentPage is not { } contentPage || - contentPage.IsItemSelected is false) - return; - - // Reset cut mode - contentPage.ItemManipulationModel.RefreshItemsOpacity(); - - if (OperatingSystem.IsLinux()) - { - // LINUX-TODO(clipboard): W-CLIP replaces the in-app FileClipboard with the system clipboard - var selected = context.SelectedItems.ToList(); - FileClipboard.Set(selected.Select(x => x.ItemPath), type); - if (type is DataPackageOperation.Move) - { - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => - { - foreach (var item in selected) - item.Opacity = Constants.UI.DimItemOpacity; - }); - } - - return; - } - - ConcurrentBag items = []; - var itemsCount = context.SelectedItems.Count; - var statusCenterItem = itemsCount > 50 ? StatusCenterHelper.AddCard_Prepare() : null; - var dataPackage = new DataPackage() { RequestedOperation = type }; - - try - { - // Update the status to in-progress - if (statusCenterItem is not null) - { - statusCenterItem.Progress.EnumerationCompleted = true; - statusCenterItem.Progress.ItemsCount = items.Count; - statusCenterItem.Progress.ReportStatus(FileSystemStatusCode.InProgress); - } - - await context.SelectedItems.ToList().ParallelForEachAsync(async listedItem => - { - // Update the status to increase processed count by one - if (statusCenterItem is not null) - { - statusCenterItem.Progress.AddProcessedItemsCount(1); - statusCenterItem.Progress.Report(); - } - - if (listedItem is FtpItem ftpItem) - { - // Don't dim selected items here since FTP doesn't support cut - if (ftpItem.PrimaryItemAttribute is StorageItemTypes.File or StorageItemTypes.Folder) - items.Add(await ftpItem.ToStorageItem()); - } - else - { - if (type is DataPackageOperation.Move) - { - // Dim opacities accordingly - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => - { - listedItem.Opacity = Constants.UI.DimItemOpacity; - }); - } - - var shellViewModel = context.ShellPage.GetRequiredShellViewModel(); - var itemPath = listedItem.GetRequiredPath(); - var result = listedItem.PrimaryItemAttribute == StorageItemTypes.File || listedItem is ZipItem - ? await shellViewModel.GetFileFromPathAsync(itemPath).OnSuccess(t => items.Add(t - ?? throw new InvalidOperationException($"The file '{itemPath}' could not be opened."))) - : await shellViewModel.GetFolderFromPathAsync(itemPath).OnSuccess(t => items.Add(t - ?? throw new InvalidOperationException($"The folder '{itemPath}' could not be opened."))); - - if (!result) - throw new SystemIO.IOException($"Failed to process {listedItem.ItemPath} in cutting/copying to the clipboard.", (int)result.ErrorCode); - } - }, 10, statusCenterItem?.CancellationToken ?? CancellationToken.None); - - var standardObjectsOnly = items.All(x => x is StorageFile or StorageFolder or SystemStorageFile or SystemStorageFolder); - if (standardObjectsOnly) - items = new(await items.ToStandardStorageItemsAsync()); - - if (items.IsEmpty) - return; - - dataPackage.Properties.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; - dataPackage.SetStorageItems(items, false); - - Clipboard.SetContent(dataPackage); - } - catch (Exception ex) - { - if (ex is not SystemIO.IOException) - App.Logger.LogWarning(ex, "Failed to process cutting/copying due to an unknown error."); - - if ((FileSystemStatusCode)ex.HResult is FileSystemStatusCode.Unauthorized) - { - var filePaths = context.SelectedItems.Select(x => x.ItemPath!).ToArray(); - await FileOperationsHelpers.SetClipboard(filePaths, type); - - return; - } - - // Reset cut mode - context.ShellPage.SlimContentPage.ItemManipulationModel.RefreshItemsOpacity(); - } - finally - { - if (statusCenterItem is not null) - statusViewModel.RemoveItem(statusCenterItem); - } - } - } -} diff --git a/src/Files.App/Helpers/TransferHelpers.cs b/src/Files.App/Helpers/TransferHelpers.cs index 31a2c7147ffb..7b4dda755501 100644 --- a/src/Files.App/Helpers/TransferHelpers.cs +++ b/src/Files.App/Helpers/TransferHelpers.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Microsoft.Extensions.Logging; using Windows.ApplicationModel.DataTransfer; using Files.App.Services.Desktop; @@ -50,4 +49,3 @@ private static async Task PublishToSystemClipboardAsync(string[] paths, DataPack } } } -#endif diff --git a/src/Files.App/Helpers/UI/UIFilesystemHelpers.cs b/src/Files.App/Helpers/UI/UIFilesystemHelpers.cs index 3b694dacc8a3..d80dba1c1707 100644 --- a/src/Files.App/Helpers/UI/UIFilesystemHelpers.cs +++ b/src/Files.App/Helpers/UI/UIFilesystemHelpers.cs @@ -16,13 +16,11 @@ public static class UIFilesystemHelpers { public static async Task PasteItemAsync(string destinationPath, IShellPage associatedInstance) { -#if !WINDOWS if (await Files.App.Services.Desktop.DesktopFileDragHelper.TryPasteFilesAsync(destinationPath, associatedInstance)) { associatedInstance.SlimContentPage?.ItemManipulationModel?.RefreshItemsOpacity(); return; } -#endif if (OperatingSystem.IsLinux() && FileClipboard.HasItems) { // Fallback when the system clipboard is unavailable (no X selection access) @@ -346,17 +344,6 @@ public async static Task RequestPassword(IPasswordProtectedIt var credentialDialogViewModel = new CredentialDialogViewModel() { CanBeAnonymous = isFtp, PasswordOnly = !isFtp }; -#if WINDOWS - if (sender is ZipStorageFolder zipFolder) - { - credentialDialogViewModel.PasswordValidator = async (password) => - { - zipFolder.Credentials = new StorageCredential(null, Encoding.UTF8.GetString(password.Bytes)); - return await Task.Run(zipFolder.ValidateCredentialsAsync); - }; - } - -#endif IDialogService dialogService = Ioc.Default.GetRequiredService(); var dialogResult = await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => dialogService.ShowDialogAsync(credentialDialogViewModel)); diff --git a/src/Files.App/Helpers/UI/UIHelpers.cs b/src/Files.App/Helpers/UI/UIHelpers.cs index 6604f6aa4847..f79def09f6b9 100644 --- a/src/Files.App/Helpers/UI/UIHelpers.cs +++ b/src/Files.App/Helpers/UI/UIHelpers.cs @@ -213,47 +213,18 @@ public static void CloseAllDialogs() private static IEnumerable LoadSidebarIconResources() { -#if WINDOWS - string imageres = Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll"); - var imageResList = Win32Helper.ExtractSelectedIconsFromDLL(imageres, new List() { - Constants.ImageRes.RecycleBin, - Constants.ImageRes.Network, - Constants.ImageRes.Folder - }, 32); - - return imageResList; -#else // LINUX-TODO(icons): imageres.dll icons do not exist on Linux return []; -#endif } private static IconFileInfo? LoadShieldIconResource() { -#if WINDOWS - string imageres = Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll"); - var imageResList = Win32Helper.ExtractSelectedIconsFromDLL(imageres, new List() { - Constants.ImageRes.ShieldIcon - }, 16); - - return imageResList.FirstOrDefault(); -#else return null; -#endif } private static IconFileInfo? LoadSearchIconResource() { -#if WINDOWS - string imageres = Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll"); - var imageResList = Win32Helper.ExtractSelectedIconsFromDLL(imageres, new List() { - Constants.ImageRes.SearchIcon - }, 48); - - return imageResList.FirstOrDefault(); -#else return null; -#endif } /// @@ -261,13 +232,9 @@ private static IEnumerable LoadSidebarIconResources() /// public static bool TryGetCursorPosition(out System.Drawing.Point point) { -#if WINDOWS - return Windows.Win32.PInvoke.GetCursorPos(out point); -#else // LINUX-TODO(cursor): Uno has no global cursor position point = default; return false; -#endif } /// @@ -276,11 +243,7 @@ public static bool TryGetCursorPosition(out System.Drawing.Point point) public static bool TryGetMainWindowClientOrigin(out System.Drawing.Point origin) { origin = new System.Drawing.Point(0, 0); -#if WINDOWS - return Windows.Win32.PInvoke.ClientToScreen(new(MainWindow.Instance.WindowHandle), ref origin); -#else return false; -#endif } } } diff --git a/src/Files.App/Helpers/Win32/Win32Helper.Process.cs b/src/Files.App/Helpers/Win32/Win32Helper.Process.cs deleted file mode 100644 index 390c38dfc9d3..000000000000 --- a/src/Files.App/Helpers/Win32/Win32Helper.Process.cs +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.RestartManager; - -namespace Files.App.Helpers -{ - /// - /// Provides static helper for Win32. - /// - public static partial class Win32Helper - { - public static async Task InvokeWin32ComponentAsync(string applicationPath, IShellPage? associatedInstance, string? arguments = null, bool runAsAdmin = false, string? workingDirectory = null) - { - return await InvokeWin32ComponentsAsync(applicationPath.CreateEnumerable(), associatedInstance, arguments, runAsAdmin, workingDirectory); - } - - public static async Task InvokeWin32ComponentsAsync(IEnumerable applicationPaths, IShellPage? associatedInstance, string? arguments = null, bool runAsAdmin = false, string? workingDirectory = null) - { - var application = applicationPaths.FirstOrDefault(); - - if (string.IsNullOrEmpty(workingDirectory) && - associatedInstance?.ShellViewModel is { IsSearchResults: false } shellViewModel) - { - workingDirectory = shellViewModel.WorkingDirectory; - } - - if (runAsAdmin) - { - // TODO In the long run, we should consider modifying HandleApplicationLaunch to handle this correctly. - try - { - ProcessStartInfo startInfo = new ProcessStartInfo - { - FileName = application - ?? throw new InvalidOperationException("No application path was provided."), - Arguments = arguments ?? string.Empty, - Verb = "runas", - WorkingDirectory = workingDirectory ?? string.Empty, - UseShellExecute = true - }; - - Process process = new Process - { - StartInfo = startInfo - }; - - process.Start(); - - return true; - } - catch (Exception) - { - return false; - } - } - else - { - return await LaunchHelper.LaunchAppAsync(application - ?? throw new InvalidOperationException("No application path was provided."), arguments, workingDirectory); - } - } - - /// - /// Gets process(es) that have a lock on the specified file. - /// - /// Path of the file. - /// Processes locking the file. - /// - /// For more info, visit - ///
- /// - - ///
- /// -
- ///
- public static List WhoIsLocking(string[] resources) - { - Span key = stackalloc char[64]; - Guid.NewGuid().TryFormat(key, out var charsWritten); - key = key[..charsWritten]; - List processes = []; - - WIN32_ERROR res = PInvoke.RmStartSession(out uint handle, key); - if (res != WIN32_ERROR.NO_ERROR) throw new Exception("Could not begin restart session. Unable to determine file locker."); - - try - { - uint pnProcInfo = 0; - uint lpdwRebootReasons; - - res = PInvoke.RmRegisterResources(handle, resources, [], []); - - if (res != WIN32_ERROR.NO_ERROR) throw new Exception("Could not register resource."); - - // Note: - // There's a race condition here -- the first call to RmGetList() returns the total number of process. - // However, when we call RmGetList() again to get the actual processes this number may have increased. - res = PInvoke.RmGetList(handle, out uint pnProcInfoNeeded, ref pnProcInfo, [], out lpdwRebootReasons); - - if (res == WIN32_ERROR.ERROR_MORE_DATA) - { - // Create an array to store the process results - var processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded]; - pnProcInfo = pnProcInfoNeeded; - - // Get the list - res = PInvoke.RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, out lpdwRebootReasons); - if (res == WIN32_ERROR.NO_ERROR) - { - processes = new List((int)pnProcInfo); - - // Enumerate all of the results and add them to the - // list to be returned - for (int i = 0; i < pnProcInfo; i++) - { - try - { - processes.Add(Process.GetProcessById((int)processInfo[i].Process.dwProcessId)); - } - // catch the error -- in case the process is no longer running - catch (ArgumentException) { } - } - } - else throw new Exception("Could not list processes locking resource."); - } - else if (res != WIN32_ERROR.NO_ERROR) throw new Exception("Could not list processes locking resource. Failed to get size of result."); - } - finally - { - _ = PInvoke.RmEndSession(handle); - } - - return processes; - } - } -} diff --git a/src/Files.App/Helpers/Win32/Win32Helper.Shell.cs b/src/Files.App/Helpers/Win32/Win32Helper.Shell.cs deleted file mode 100644 index 45ad1104f9c1..000000000000 --- a/src/Files.App/Helpers/Win32/Win32Helper.Shell.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -using System.IO; -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; - -namespace Files.App.Helpers -{ - /// - /// Provides static helper for Win32. - /// - public static partial class Win32Helper - { - public static async Task<(ShellFileItem? Folder, List Enumerate)> GetShellFolderAsync(string path, bool getFolder, bool getEnumerate, int from, int count, params string[] properties) - { - if (path.StartsWith("::{", StringComparison.Ordinal)) - { - path = $"shell:{path}"; - } - - return await STATask.Run(() => - { - var flc = new List(); - ShellFileItem? folder = null; - - try - { - using var shellFolder = ShellFolderExtensions.GetShellItemFromPathOrPIDL(path) as ShellFolder; - using ShellFolder _controlPanel = new(PInvoke.FOLDERID_ControlPanelFolder); - using ShellFolder _controlPanelCategoryView = new("::{26EE0668-A00A-44D7-9371-BEB064C98683}"); - - if (shellFolder is null || - (_controlPanel.PIDL.IsParentOf(shellFolder.PIDL, false) || - _controlPanelCategoryView.PIDL.IsParentOf(shellFolder.PIDL, false)) && - !shellFolder.Any()) - { - // Return null to force open unsupported items in explorer - // only if inside control panel and folder appears empty - return (null, flc); - } - - if (getFolder) - folder = ShellFolderExtensions.GetShellFileItem(shellFolder); - - if (getEnumerate) - { - foreach (var folderItem in shellFolder.Skip(from).Take(count)) - { - try - { - var shellFileItem = folderItem is Files.App.Utils.Shell.ShellLink link ? - ShellFolderExtensions.GetShellLinkItem(link) : - ShellFolderExtensions.GetShellFileItem(folderItem); - if (shellFileItem is null) - continue; - - foreach (var prop in properties) - shellFileItem.Properties[prop] = SafetyExtensions.IgnoreExceptions(() => folderItem.Properties[prop]); - - flc.Add(shellFileItem); - } - catch (Exception ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException) - { - // Happens if files are being deleted - } - finally - { - folderItem.Dispose(); - } - } - } - } - catch - { - } - - return (folder, flc); - }, App.Logger); - } - - public static unsafe string GetFolderFromKnownFolderGUID(Guid guid) - { - PWSTR pszPath; - PInvoke.SHGetKnownFolderPath(in guid, (KNOWN_FOLDER_FLAG)0, null, out pszPath); - string path = pszPath.ToString(); - Marshal.FreeCoTaskMem((nint)pszPath.Value); - - return path; - } - } -} diff --git a/src/Files.App/Helpers/Win32/Win32Helper.Storage.cs b/src/Files.App/Helpers/Win32/Win32Helper.Storage.cs deleted file mode 100644 index 201f3121e388..000000000000 --- a/src/Files.App/Helpers/Win32/Win32Helper.Storage.cs +++ /dev/null @@ -1,1235 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -using Microsoft.Extensions.Logging; -using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; -using System.Collections.Concurrent; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using Windows.System; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Gdi; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.UI.Controls; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; -using COMPRESSION_FORMAT = Windows.Win32.Storage.FileSystem.COMPRESSION_FORMAT; -using HRESULT = Windows.Win32.Foundation.HRESULT; -using HWND = Windows.Win32.Foundation.HWND; - -namespace Files.App.Helpers -{ - /// - /// Provides static helper for Win32. - /// - public static partial class Win32Helper - { - internal static string ToPowerShellStringLiteral(string? value) - => $"'{(value ?? string.Empty).Replace("'", "''", StringComparison.Ordinal)}'"; - - public static async Task GetDefaultFileAssociationAsync(string filename, bool checkDesktopFirst = true) - { - // check if there exists an user choice first - var userChoice = GetUserChoiceFileAssociation(filename); - if (!string.IsNullOrEmpty(userChoice)) - return userChoice; - - return await GetFileAssociationAsync(filename, checkDesktopFirst); - - } - - public static string ExtractStringFromDLL(string file, int number) - { - using var lib = PInvoke.LoadLibrary(file); - Span result = stackalloc char[2048]; - - int length = PInvoke.LoadString(lib, (uint)number, result, result.Length); - - return result[..length].ToString(); - } - - public static unsafe string?[] CommandLineToArgs(string commandLine) - { - if (string.IsNullOrEmpty(commandLine)) - return []; - - PWSTR* argv = PInvoke.CommandLineToArgv(commandLine, out int argc); - if (argv is null) - throw new Win32Exception(); - - try - { - var args = new string?[argc]; - for (var i = 0; i < args.Length; i++) - { - args[i] = argv[i].ToString(); - } - - return args; - } - finally - { - PInvoke.LocalFree((HLOCAL)argv); - } - } - - private static readonly Lock _iconOverlayLock = new(); - - /// - /// Returns overlay for given file or folder - /// - /// - /// - /// - // Maps a target pixel size to a system image list (SHIL_*): 16 -> SMALL, 32 -> LARGE, 48 -> EXTRALARGE, larger -> JUMBO - private static int GetImageListForSize(int size) => size switch - { - <= 16 => 1, - <= 32 => 0, - <= 48 => 2, - _ => 4, - }; - - public static byte[]? GetIconOverlay(string? path, int size, bool isDirectory) - { - if (path is null) - return null; - - SHFILEINFOW shFileInfo = default; - const SHGFI_FLAGS flags = SHGFI_FLAGS.SHGFI_OVERLAYINDEX | SHGFI_FLAGS.SHGFI_ICON | SHGFI_FLAGS.SHGFI_SYSICONINDEX | SHGFI_FLAGS.SHGFI_ICONLOCATION; - byte[]? overlayData = null; - - try - { - nuint result = PInvoke.SHGetFileInfo(path, isDirectory ? FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_DIRECTORY : 0, ref shFileInfo, flags); - if (result is 0) - return null; - - PInvoke.DestroyIcon(shFileInfo.hIcon); - - lock (_iconOverlayLock) - { - if (PInvoke.SHGetImageList(GetImageListForSize(size), out var imageList).Failed) - return null; - - var overlayIdx = shFileInfo.iIcon >> 24; - if (overlayIdx != 0) - { - imageList.GetOverlayImage(overlayIdx, out int overlayImage).ThrowOnFailure(); - imageList.GetIcon(overlayImage, 1, out var overlayHandle).ThrowOnFailure(); - using var hOverlay = overlayHandle; - - if (!hOverlay.IsClosed && !hOverlay.IsInvalid) - { - using var image = GetBitmapFromHIcon(hOverlay); - if (image is null) - return null; - overlayData = (byte[]?)new ImageConverter().ConvertTo(image, typeof(byte[])); - } - } - } - } - catch (Exception) - { - return null; - } - - return overlayData; - } - - private static readonly Lock _iconLock = new(); - - /// - /// Returns an icon if returnIconOnly is true, otherwise a thumbnail will be returned if available. - /// - /// - /// - /// - /// - /// - public static unsafe byte[]? GetIcon( - string? path, - int size, - bool isFolder, - IconOptions iconOptions) - { - if (string.IsNullOrWhiteSpace(path)) - return null; - - byte[]? iconData = null; - - try - { - // Attempt to get file icon/thumbnail using IShellItemImageFactory GetImage - using var shellItem = SafetyExtensions.IgnoreExceptions(() - => ShellFolderExtensions.GetShellItemFromPathOrPIDL(path)); - - if (shellItem is not null && shellItem.IShellItem is IShellItemImageFactory shellFactory) - { - var flags = SIIGBF.SIIGBF_BIGGERSIZEOK; - - if (iconOptions.HasFlag(IconOptions.ReturnIconOnly)) - flags |= SIIGBF.SIIGBF_ICONONLY; - - if (iconOptions.HasFlag(IconOptions.ReturnThumbnailOnly)) - flags |= SIIGBF.SIIGBF_THUMBNAILONLY; - - if (iconOptions.HasFlag(IconOptions.ReturnOnlyIfCached)) - flags |= SIIGBF.SIIGBF_INCACHEONLY; - - HBITMAP hbitmap = default; - var hres = shellFactory.GetImage(new(size, size), flags, &hbitmap); - try - { - if (hres == HRESULT.S_OK) - { - using var image = GetBitmapFromHBitmap(hbitmap); - if (image is not null) - iconData = (byte[]?)new ImageConverter().ConvertTo(image, typeof(byte[])); - } - } - finally - { - if (!hbitmap.IsNull) - PInvoke.DeleteObject(hbitmap); - } - } - - if (iconData is not null || iconOptions.HasFlag(IconOptions.ReturnThumbnailOnly)) - return iconData; - else - { - SHFILEINFOW shfi = default; - const SHGFI_FLAGS flags = SHGFI_FLAGS.SHGFI_OVERLAYINDEX | SHGFI_FLAGS.SHGFI_ICON | SHGFI_FLAGS.SHGFI_SYSICONINDEX | SHGFI_FLAGS.SHGFI_ICONLOCATION | SHGFI_FLAGS.SHGFI_USEFILEATTRIBUTES; - - // Cannot access file, use file attributes - var ret = PInvoke.SHGetFileInfo(path, isFolder ? FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_DIRECTORY : 0, ref shfi, flags); - if (ret is 0) - return iconData; - - PInvoke.DestroyIcon(shfi.hIcon); - - var imageListSize = GetImageListForSize(size); - - lock (_iconLock) - { - if (PInvoke.SHGetImageList(imageListSize, out var imageList).Failed) - return iconData; - - if (iconData is null) - { - var iconIdx = shfi.iIcon & 0xFFFFFF; - if (iconIdx != 0) - { - // Could not fetch thumbnail, load simple icon - imageList.GetIcon(iconIdx, 1, out var iconHandle).ThrowOnFailure(); - using var hIcon = iconHandle; - if (!hIcon.IsClosed && !hIcon.IsInvalid) - { - using (var image = GetBitmapFromHIcon(hIcon)) - { - if (image is not null) - iconData = (byte[]?)new ImageConverter().ConvertTo(image, typeof(byte[])); - } - } - } - else if (isFolder) - { - // Could not icon, load generic icon - var icons = ExtractSelectedIconsFromDLL(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "imageres.dll"), [2], size); - var generic = icons.SingleOrDefault(x => x.Index == 2); - iconData = generic?.IconData; - } - else - { - // Could not icon, load generic icon - var icons = ExtractSelectedIconsFromDLL(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "shell32.dll"), [1], size); - var generic = icons.SingleOrDefault(x => x.Index == 1); - iconData = generic?.IconData; - } - } - } - - return iconData; - } - } - finally - { - - } - } - - public static async Task RunPowershellCommandAsync(string command, PowerShellExecutionOptions options, string? workingDirectory = null) - { - using Process process = CreatePowershellProcess(command, options, workingDirectory); - using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(30 * 1000)); - - try - { - process.Start(); - await process.WaitForExitAsync(cts.Token); - return process.ExitCode == 0; - } - catch (OperationCanceledException) - { - return false; - } - catch (InvalidOperationException ex) - { - App.Logger.LogWarning(ex, ex.Message); - return false; - } - catch (Win32Exception) - { - // If user cancels UAC - return false; - } - } - - public static bool RunPowershellCommand(string command, PowerShellExecutionOptions options, string? workingDirectory = null) - { - try - { - using Process process = CreatePowershellProcess(command, options, workingDirectory); - - process.Start(); - - if (process.WaitForExit(30 * 1000)) - return process.ExitCode == 0; - - return false; - } - catch (Win32Exception) - { - // If user cancels UAC - return false; - } - } - - private static readonly ConcurrentDictionary<(string File, int Index, int Size), IconFileInfo> _iconCache = new(); - - public static IList ExtractSelectedIconsFromDLL(string file, IList indexes, int iconSize = 48) - { - var iconsList = new List(); - - // PE resource icons do not exist on Linux; callers fall back to theme icons via IIconThemeProvider - if (!OperatingSystem.IsWindows()) - return iconsList; - - foreach (int index in indexes) - { - if (_iconCache.TryGetValue((file, index, iconSize), out var iconInfo)) - { - iconsList.Add(iconInfo); - } - else - { - // This is merely to pass into the function and is unneeded otherwise - var result = PInvoke.SHDefExtractIcon(file, -1 * index, 0, out var largeIcon, out var smallIcon, Convert.ToUInt32(iconSize)); - using var icon = largeIcon; - using var icon2 = smallIcon; - if (result == HRESULT.S_OK) - { - using var image = GetBitmapFromHIcon(icon); - if (image is null) - continue; - byte[] bitmapData = (byte[])(new ImageConverter().ConvertTo(image, typeof(byte[])) ?? Array.Empty()); - iconInfo = new IconFileInfo(bitmapData, index); - _iconCache[(file, index, iconSize)] = iconInfo; - iconsList.Add(iconInfo); - } - } - } - - return iconsList; - } - - public static IList? ExtractIconsFromDLL(string file) - { - var iconsList = new List(); - - using var icoCnt = PInvoke.ExtractIcon(file, uint.MaxValue); - if (icoCnt.IsInvalid) - return null; - - int count = icoCnt.DangerousGetHandle().ToInt32(); - icoCnt.SetHandleAsInvalid(); - if (count <= 0) - return null; - - for (int i = 0; i < count; i++) - { - if (_iconCache.TryGetValue((file, i, -1), out var iconInfo)) - { - iconsList.Add(iconInfo); - } - else - { - using var icon = PInvoke.ExtractIcon(file, (uint)i); - using var image = GetBitmapFromHIcon(icon); - if (image is null) - continue; - - byte[] bitmapData = (byte[])(new ImageConverter().ConvertTo(image, typeof(byte[])) ?? Array.Empty()); - iconInfo = new IconFileInfo(bitmapData, i); - _iconCache[(file, i, -1)] = iconInfo; - iconsList.Add(iconInfo); - } - } - - return iconsList; - } - - public static unsafe bool SetCustomDirectoryIcon(string? folderPath, string? iconFile, int iconIndex = 0) - { - if (folderPath is null) - return false; - - fixed (char* iconPath = iconFile) - { - SHFOLDERCUSTOMSETTINGS settings = new() - { - dwSize = (uint)sizeof(SHFOLDERCUSTOMSETTINGS), - dwMask = PInvoke.FCSM_ICONFILE, - pszIconFile = iconPath, - iIconIndex = iconIndex, - }; - return PInvoke.SHGetSetFolderCustomSettings(ref settings, folderPath, PInvoke.FCS_FORCEWRITE).Succeeded; - } - } - - public static bool SetCustomFileIcon(string? filePath, string? iconFile, int iconIndex = 0) - { - if (filePath is null) - return false; - - var success = FileOperationsHelpers.SetLinkIcon(filePath, iconFile, iconIndex); - - return success; - } - - public static bool ConvertImageToIcoFile(string imagePath, string icoFilePath) - { - try - { - using var sourceImage = new Bitmap(imagePath); - - // ICO frames are capped at 256x256; don't upscale sources smaller than a standard frame size - int largestFrameSize = Math.Min(Math.Max(sourceImage.Width, sourceImage.Height), 256); - int[] frameSizes = [.. new[] { 16, 24, 32, 48, 256 }.Where(size => size < largestFrameSize), largestFrameSize]; - - var pngFrames = new List(frameSizes.Length); - foreach (int size in frameSizes) - { - using var frame = new Bitmap(size, size, PixelFormat.Format32bppArgb); - using var graphics = Graphics.FromImage(frame); - graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; - graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - - // Fit into the square frame preserving aspect ratio, centered on a transparent background - double scale = Math.Min((double)size / sourceImage.Width, (double)size / sourceImage.Height); - int scaledWidth = Math.Max(1, (int)Math.Round(sourceImage.Width * scale)); - int scaledHeight = Math.Max(1, (int)Math.Round(sourceImage.Height * scale)); - graphics.DrawImage(sourceImage, (size - scaledWidth) / 2, (size - scaledHeight) / 2, scaledWidth, scaledHeight); - - using var pngStream = new MemoryStream(); - frame.Save(pngStream, ImageFormat.Png); - pngFrames.Add(pngStream.ToArray()); - } - - using var icoStream = new FileStream(icoFilePath, FileMode.Create, FileAccess.Write); - using var writer = new BinaryWriter(icoStream); - - // ICONDIR header - writer.Write((ushort)0); // Reserved - writer.Write((ushort)1); // Type: icon - writer.Write((ushort)frameSizes.Length); - - // ICONDIRENTRY table; a width/height byte of 0 means 256 - int frameDataOffset = 6 + 16 * frameSizes.Length; - for (int i = 0; i < frameSizes.Length; i++) - { - byte sizeByte = (byte)(frameSizes[i] == 256 ? 0 : frameSizes[i]); - writer.Write(sizeByte); // Width - writer.Write(sizeByte); // Height - writer.Write((byte)0); // Color palette size (none) - writer.Write((byte)0); // Reserved - writer.Write((ushort)1); // Color planes - writer.Write((ushort)32); // Bits per pixel - writer.Write((uint)pngFrames[i].Length); - writer.Write((uint)frameDataOffset); - frameDataOffset += pngFrames[i].Length; - } - - // PNG-compressed frame data (supported in ICO since Windows Vista) - foreach (var frameData in pngFrames) - writer.Write(frameData); - - return true; - } - // GDI+ surfaces unsupported or corrupted image data as ArgumentException/OutOfMemoryException; IOException/UnauthorizedAccessException cover an unreadable source or unwritable destination - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Failed to convert '{ImagePath}' to an ICO file.", imagePath); - return false; - } - } - - public static Task OpenFormatDriveDialog(string drive) - { - // Format requires elevation - int driveIndex = drive.ToUpperInvariant()[0] - 'A'; - return RunPowershellCommandAsync($"-command \"$Signature = '[DllImport(\\\"shell32.dll\\\", SetLastError = false)]public static extern uint SHFormatDrive(IntPtr hwnd, uint drive, uint fmtID, uint options);'; $SHFormatDrive = Add-Type -MemberDefinition $Signature -Name \"Win32SHFormatDrive\" -Namespace Win32Functions -PassThru; $SHFormatDrive::SHFormatDrive(0, {driveIndex}, 0xFFFF, 0x0001)\"", PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - } - - public static void SetVolumeLabel(string drivePath, string newLabel) - { - // Rename requires elevation - RunPowershellCommand($"-command \"$Signature = '[DllImport(\\\"kernel32.dll\\\", SetLastError = false)]public static extern bool SetVolumeLabel(string lpRootPathName, string lpVolumeName);'; $SetVolumeLabel = Add-Type -MemberDefinition $Signature -Name \"Win32SetVolumeLabel\" -Namespace Win32Functions -PassThru; $SetVolumeLabel::SetVolumeLabel({ToPowerShellStringLiteral(drivePath)}, {ToPowerShellStringLiteral(newLabel)})\"", PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - - NotifyShellOfItemChange(drivePath); - } - - public static void SetNetworkDriveLabel(string driveName, string newLabel) - { - RunPowershellCommand($"-command \"(New-Object -ComObject Shell.Application).NameSpace({ToPowerShellStringLiteral(driveName)}).Self.Name={ToPowerShellStringLiteral(newLabel)}\"", PowerShellExecutionOptions.Hidden); - - NotifyShellOfItemChange(driveName); - } - - // Without this the shell keeps serving the cached display name - private static unsafe void NotifyShellOfItemChange(string path) - { - // The shell parser doesn't accept extended length paths - if (path.StartsWith(@"\\?\", StringComparison.Ordinal)) - path = path[4..]; - - // A bare "U:" means the current directory on that drive rather than the volume root - if (path.Length == 2 && path[1] == ':') - path += '\\'; - - fixed (char* pszPath = path) - PInvoke.SHChangeNotify(SHCNE_ID.SHCNE_UPDATEITEM, SHCNF_FLAGS.SHCNF_PATHW | SHCNF_FLAGS.SHCNF_FLUSH, pszPath, null); - } - - /// - /// Returns the localized display name from the folder's desktop.ini, or null when there is none. - /// - public static unsafe string? GetLocalizedName(string path) - { - Span resModule = stackalloc char[260]; - int resId; - - fixed (char* pszPath = path) - fixed (char* pszResModule = resModule) - { - if (PInvoke.SHGetLocalizedName(pszPath, pszResModule, (uint)resModule.Length, &resId).Failed) - return null; - } - - int moduleLength = resModule.IndexOf('\0'); - if (moduleLength <= 0) - return null; - - // A zero resource id means desktop.ini held a literal name rather than a resource reference - if (resId == 0) - return resModule[..moduleLength].ToString(); - - // SHLoadIndirectString expands environment variables in the module path - var source = $"@{resModule[..moduleLength]},-{resId}"; - Span buffer = stackalloc char[512]; - fixed (char* pszSource = source) - fixed (char* pszBuffer = buffer) - { - if (PInvoke.SHLoadIndirectString(pszSource, pszBuffer, (uint)buffer.Length, null).Failed) - return null; - } - - int length = buffer.IndexOf('\0'); - return length > 0 ? buffer[..length].ToString() : null; - } - - public static Task MountVhdDisk(string vhdPath) - { - // Mounting requires elevation - return RunPowershellCommandAsync($"-command \"Mount-DiskImage -ImagePath {ToPowerShellStringLiteral(vhdPath)}\"", PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - } - - public static Bitmap? GetBitmapFromHBitmap(HBITMAP hBitmap) - { - try - { - Bitmap bmp = Image.FromHbitmap((IntPtr)hBitmap); - if (Image.GetPixelFormatSize(bmp.PixelFormat) < 32) - return bmp; - - Rectangle bmBounds = new Rectangle(0, 0, bmp.Width, bmp.Height); - var bmpData = bmp.LockBits(bmBounds, ImageLockMode.ReadOnly, bmp.PixelFormat); - - if (IsAlphaBitmap(bmpData)) - { - var alpha = GetAlphaBitmapFromBitmapData(bmpData); - - bmp.UnlockBits(bmpData); - bmp.Dispose(); - - return alpha; - } - - bmp.UnlockBits(bmpData); - - return bmp; - } - catch - { - return null; - } - } - - private static Bitmap? GetBitmapFromHIcon(SafeHandle iconHandle) - { - if (iconHandle.IsInvalid || iconHandle.IsClosed) - return null; - - try - { - using var icon = (Icon)Icon.FromHandle(iconHandle.DangerousGetHandle()).Clone(); - return icon.ToBitmap(); - } - catch - { - return null; - } - } - - public static ITaskbarList4? CreateTaskbarObject() - { - try - { - var taskbar = TaskbarList.CreateInstance(); - taskbar.HrInit().ThrowOnFailure(); - return taskbar; - } - catch (Exception) - { - // explorer.exe is not running as a shell - return null; - } - } - - private static Bitmap GetAlphaBitmapFromBitmapData(BitmapData bmpData) - { - using var tmp = new Bitmap(bmpData.Width, bmpData.Height, bmpData.Stride, PixelFormat.Format32bppArgb, bmpData.Scan0); - Bitmap clone = new Bitmap(tmp.Width, tmp.Height, tmp.PixelFormat); - - using (Graphics gr = Graphics.FromImage(clone)) - { - gr.DrawImage(tmp, new Rectangle(0, 0, clone.Width, clone.Height)); - } - - return clone; - } - - private static bool IsAlphaBitmap(BitmapData bmpData) - { - for (int y = 0; y <= bmpData.Height - 1; y++) - { - for (int x = 0; x <= bmpData.Width - 1; x++) - { - Color pixelColor = Color.FromArgb( - Marshal.ReadInt32(bmpData.Scan0, (bmpData.Stride * y) + (4 * x))); - - if (pixelColor.A < 255) - return true; - } - } - - return false; - } - - public static IEnumerable GetDesktopWindows() - { - HWND prevHwnd = HWND.Null; - var windowsList = new List(); - - while (true) - { - prevHwnd = PInvoke.FindWindowEx(HWND.Null, prevHwnd, null, null); - if (prevHwnd == HWND.Null) - break; - - windowsList.Add(prevHwnd); - } - - return windowsList; - } - - public static void BringToForeground(IEnumerable currentWindows) - { - CancellationTokenSource cts = new CancellationTokenSource(); - cts.CancelAfter(5 * 1000); - - Task.Run(async () => - { - while (!cts.IsCancellationRequested) - { - await Task.Delay(500); - - var newWindows = GetDesktopWindows().Except(currentWindows).Where(x => PInvoke.IsWindowVisible(x) && !PInvoke.IsIconic(x)); - if (newWindows.Any()) - { - foreach (var newWindow in newWindows) - { - PInvoke.SetWindowPos( - newWindow, - (HWND)(-1), - 0, 0, 0, 0, - SET_WINDOW_POS_FLAGS.SWP_NOSIZE | SET_WINDOW_POS_FLAGS.SWP_NOMOVE); - - PInvoke.SetWindowPos( - newWindow, - (HWND)(-2), - 0, 0, 0, 0, - SET_WINDOW_POS_FLAGS.SWP_SHOWWINDOW | SET_WINDOW_POS_FLAGS.SWP_NOSIZE | SET_WINDOW_POS_FLAGS.SWP_NOMOVE); - } - - break; - } - } - }); - } - - /// - /// Gets file path from file FRN - /// - /// File reference number - /// Drive containing the file (e.g. "C:\") - /// File path or null - public static string? PathFromFileId(ulong frn, string volumeHint) - { - string? volumePath = Path.GetPathRoot(volumeHint); - if (string.IsNullOrEmpty(volumePath)) - return null; - - using var volumeHandle = PInvoke.CreateFile(volumePath, (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_READ, FILE_SHARE_MODE.FILE_SHARE_READ, null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, null); - if (volumeHandle.IsInvalid) - return null; - - FILE_ID_DESCRIPTOR fileId = new() { dwSize = (uint)Marshal.SizeOf(), Type = FILE_ID_TYPE.FileIdType }; - fileId.FileId = (long)frn; - - using var hFile = PInvoke.OpenFileById(volumeHandle, fileId, (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_READ, FILE_SHARE_MODE.FILE_SHARE_READ, null, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS); - if (hFile.IsInvalid) - return null; - - Span path = stackalloc char[4096]; - uint length = PInvoke.GetFinalPathNameByHandle(hFile, path, GETFINALPATHNAMEBYHANDLE_FLAGS.FILE_NAME_NORMALIZED | GETFINALPATHNAMEBYHANDLE_FLAGS.VOLUME_NAME_DOS); - return length is > 0 and < 4096 ? path[..(int)length].ToString() : null; - } - - public static unsafe void OpenFolderInExistingShellWindow(string folderPath) - { - if (TryOpenFolderInExistingShellWindow(folderPath)) - return; - - string operation = "open"; - string explorerPath = Environment.ExpandEnvironmentVariables("%windir%\\explorer.exe"); - fixed (char* operationPointer = operation, explorerPointer = explorerPath, folderPointer = folderPath) - PInvoke.ShellExecute(HWND.Null, operationPointer, explorerPointer, folderPointer, null, SHOW_WINDOW_CMD.SW_SHOWNORMAL); - } - - private static bool TryOpenFolderInExistingShellWindow(string folderPath) - { - try - { - using var target = SafetyExtensions.IgnoreExceptions(() => ShellFolderExtensions.GetShellItemFromPathOrPIDL(folderPath)); - if (target is null) - return false; - - using var controlPanelCategoryView = new ShellItem("::{26EE0668-A00A-44D7-9371-BEB064C98683}"); - using var shellWindows = new ShellWindowsAutomation(); - int count = shellWindows.Count; - for (int index = 0; index < count; index++) - { - using var window = shellWindows.GetWindow(index); - if (window?.TryNavigate(target.PIDL, controlPanelCategoryView.PIDL) is true) - return true; - } - } - catch (Exception exception) - { - Debug.WriteLine(exception); - } - - return false; - } - - public static async Task InstallInf(string? filePath) - { - try - { - var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(30 * 1000)); - - using Process process = new(); - process.StartInfo.FileName = "InfDefaultInstall.exe"; - process.StartInfo.Verb = "runas"; - process.StartInfo.UseShellExecute = true; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.Arguments = $"\"{filePath}\""; - process.Start(); - - await process.WaitForExitAsync(cts.Token); - - return true; - } - catch - { - return false; - } - } - - public static async Task InstallFontsAsync(string[] fontFilePaths, bool forAllUsers) - { - string fontDirectory = forAllUsers - ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts") - : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft", "Windows", "Fonts"); - - string registryKey = forAllUsers - ? "HKLM:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts" - : "HKCU:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"; - - var psCommand = new StringBuilder("-command \""); - - foreach (string fontFilePath in fontFilePaths) - { - var destinationPath = Path.Combine(fontDirectory, Path.GetFileName(fontFilePath)); - var appendCommand = $"Copy-Item {ToPowerShellStringLiteral(fontFilePath)} {ToPowerShellStringLiteral(fontDirectory)}; New-ItemProperty -Name {ToPowerShellStringLiteral(Path.GetFileNameWithoutExtension(fontFilePath))} -Path {ToPowerShellStringLiteral(registryKey)} -PropertyType string -Value {ToPowerShellStringLiteral(destinationPath)};"; - - if (psCommand.Length + appendCommand.Length > 32766) - { - // The command is too long to run at once, so run the command once up to this point. - await RunPowershellCommandAsync(psCommand.Append('"').ToString(), PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - psCommand.Clear().Append("-command \""); - } - - psCommand.Append(appendCommand); - } - - await RunPowershellCommandAsync(psCommand.Append('"').ToString(), PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - } - - private static Process CreatePowershellProcess(string command, PowerShellExecutionOptions options, string? workingDirectory = null) - { - Process process = new(); - - process.StartInfo.FileName = "powershell.exe"; - if (options.HasFlag(PowerShellExecutionOptions.Elevated)) - { - process.StartInfo.UseShellExecute = true; - process.StartInfo.Verb = "runas"; - } - - if (options.HasFlag(PowerShellExecutionOptions.Hidden)) - { - process.StartInfo.CreateNoWindow = true; - process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; - } - - if (workingDirectory is not null) - process.StartInfo.WorkingDirectory = workingDirectory; - - process.StartInfo.Arguments = command; - - return process; - } - - public static SafeFileHandle CreateFileForWrite(string filePath, bool overwrite = true) - { - return PInvoke.CreateFile(filePath, - (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE, 0, null, overwrite ? FILE_CREATION_DISPOSITION.CREATE_ALWAYS : FILE_CREATION_DISPOSITION.OPEN_ALWAYS, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, null); - } - - public static SafeFileHandle OpenFileForRead(string filePath, bool readWrite = false, uint flags = 0) - { - return PInvoke.CreateFile(filePath, - (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | (uint)(readWrite ? FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE : 0u), FILE_SHARE_MODE.FILE_SHARE_READ | (readWrite ? 0 : FILE_SHARE_MODE.FILE_SHARE_WRITE), null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS | (FILE_FLAGS_AND_ATTRIBUTES)flags, null); - } - - public static bool GetFileDateModified(string filePath, out System.Runtime.InteropServices.ComTypes.FILETIME dateModified) - { - using var hFile = PInvoke.CreateFile(filePath, (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_READ, FILE_SHARE_MODE.FILE_SHARE_READ, null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, null); - return PInvoke.GetFileTime(hFile, out _, out _, out dateModified); - } - - public static bool SetFileDateModified(string filePath, System.Runtime.InteropServices.ComTypes.FILETIME dateModified) - { - using var hFile = PInvoke.CreateFile(filePath, (uint)FILE_ACCESS_RIGHTS.FILE_WRITE_ATTRIBUTES, 0, null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, null); - return PInvoke.SetFileTime(hFile, null, null, dateModified); - } - - public static FileAttributes GetFileAttributes(string lpFileName) - { - uint attributes = PInvoke.GetFileAttributes(lpFileName); - return attributes == PInvoke.INVALID_FILE_ATTRIBUTES ? FileAttributes.None : (FileAttributes)attributes; - } - - public static bool HasFileAttribute(string lpFileName, FileAttributes dwAttrs) - { - Debug.Assert(dwAttrs != FileAttributes.None); - - return GetFileAttributes(lpFileName).HasFlag(dwAttrs); - } - - public static bool SetFileAttribute(string lpFileName, FileAttributes dwAttrs) - { - uint attributes = PInvoke.GetFileAttributes(lpFileName); - if (attributes == PInvoke.INVALID_FILE_ATTRIBUTES) - return false; - return PInvoke.SetFileAttributes(lpFileName, (FILE_FLAGS_AND_ATTRIBUTES)(attributes | (uint)dwAttrs)); - } - - public static bool UnsetFileAttribute(string lpFileName, FileAttributes dwAttrs) - { - uint attributes = PInvoke.GetFileAttributes(lpFileName); - if (attributes == PInvoke.INVALID_FILE_ATTRIBUTES) - return false; - return PInvoke.SetFileAttributes(lpFileName, (FILE_FLAGS_AND_ATTRIBUTES)(attributes & ~(uint)dwAttrs)); - } - - public static unsafe bool CanCompressContent(string path) - { - path = Path.GetPathRoot(path) ?? string.Empty; - uint dwFileSystemFlags = 0; - - var success = PInvoke.GetVolumeInformation( - path, - [], - out _, - out _, - out dwFileSystemFlags, - []); - - if (!success) - return false; - - return (dwFileSystemFlags & PInvoke.FILE_FILE_COMPRESSION) != 0; - } - - public static unsafe bool SetCompressionAttributeIoctl(string lpFileName, bool isCompressed) - { - // GENERIC_READ | GENERIC_WRITE flags are needed here - // FILE_FLAG_BACKUP_SEMANTICS is used to open directories - using var hFile = PInvoke.CreateFile( - lpFileName, - (uint)(FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE | FILE_ACCESS_RIGHTS.FILE_WRITE_ATTRIBUTES), - FILE_SHARE_MODE.FILE_SHARE_READ | FILE_SHARE_MODE.FILE_SHARE_WRITE, - lpSecurityAttributes: null, - FILE_CREATION_DISPOSITION.OPEN_EXISTING, - FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_NORMAL | FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, - hTemplateFile: null); - - if (hFile.IsInvalid) - return false; - - var bytesReturned = 0u; - var compressionFormat = isCompressed - ? COMPRESSION_FORMAT.COMPRESSION_FORMAT_DEFAULT - : COMPRESSION_FORMAT.COMPRESSION_FORMAT_NONE; - - var result = PInvoke.DeviceIoControl( - new(hFile.DangerousGetHandle()), - PInvoke.FSCTL_SET_COMPRESSION, - &compressionFormat, - sizeof(ushort), - null, - 0u, - &bytesReturned); - - return result; - } - - public static string? ReadStringFromFile(string filePath) - { -#if !WINDOWS - // LINUX-TODO(ads): only NTFS alternate data streams ("file:stream") used this on Windows; settings use System.IO directly. - return null; -#else - try - { - using SafeFileHandle hFile = OpenFileForRead(filePath); - if (hFile.IsInvalid) - return null; - - using FileStream stream = new(hFile, FileAccess.Read); - using StreamReader reader = new(stream, detectEncodingFromByteOrderMarks: true); - return reader.ReadToEnd(); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - return null; - } -#endif - } - - public static bool WriteStringToFile(string filePath, string str, FILE_FLAGS_AND_ATTRIBUTES flags = 0) - { -#if !WINDOWS - // LINUX-TODO(ads): alternate data streams do not exist on Linux (could map to xattrs) - return false; -#else - try - { - using SafeFileHandle hStream = PInvoke.CreateFile(filePath, - (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE, 0, null, FILE_CREATION_DISPOSITION.CREATE_ALWAYS, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS | flags, null); - if (hStream.IsInvalid) - return false; - - using FileStream stream = new(hStream, FileAccess.Write); - stream.Write(Encoding.UTF8.GetBytes(str)); - return true; - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - return false; - } -#endif - } - - // https://www.pinvoke.net/default.aspx/kernel32/GetFileInformationByHandleEx.html - public static ulong? GetFolderFRN(string? folderPath) - { - if (string.IsNullOrEmpty(folderPath)) - return null; - - // LINUX-TODO(frn): NTFS file reference numbers; could use st_ino/st_dev - if (!OperatingSystem.IsWindows()) - return null; - - using var handle = OpenFileForRead(folderPath); - if (!handle.IsInvalid) - { - FILE_ID_BOTH_DIR_INFO fileId = default; - if (PInvoke.GetFileInformationByHandleEx(handle, FILE_INFO_BY_HANDLE_CLASS.FileIdBothDirectoryInfo, MemoryMarshal.AsBytes(new Span(ref fileId)))) - return (ulong)fileId.FileId; - } - return null; - } - - public static unsafe ulong? GetFileFRN(string filePath) - { - if (!OperatingSystem.IsWindows()) - return null; - - using var handle = OpenFileForRead(filePath); - if (!handle.IsInvalid) - { - try - { - FILE_ID_INFO fileId = default; - if (PInvoke.GetFileInformationByHandleEx(handle, FILE_INFO_BY_HANDLE_CLASS.FileIdInfo, MemoryMarshal.AsBytes(new Span(ref fileId)))) - return BitConverter.ToUInt64(fileId.FileId.Identifier.AsReadOnlySpan()); - } - catch { } - } - return null; - } - - public static long? GetFileSizeOnDisk(string filePath) - { - if (!OperatingSystem.IsWindows()) - return null; - - using var handle = OpenFileForRead(filePath); - if (!handle.IsInvalid) - { - try - { - FILE_STANDARD_INFO fileInfo = default; - if (PInvoke.GetFileInformationByHandleEx(handle, FILE_INFO_BY_HANDLE_CLASS.FileStandardInfo, MemoryMarshal.AsBytes(new Span(ref fileInfo)))) - return fileInfo.AllocationSize; - } - catch { } - } - return null; - } - - // https://github.com/rad1oactive/BetterExplorer/blob/master/Windows%20API%20Code%20Pack%201.1/source/WindowsAPICodePack/Shell/ReparsePoint.cs - public static unsafe string? ParseSymLink(string path) - { - using var handle = OpenFileForRead(path, false, 0x00200000); - if (!handle.IsInvalid) - { - byte[] buffer = new byte[16 * 1024]; - if (PInvoke.DeviceIoControl(handle, PInvoke.FSCTL_GET_REPARSE_POINT, [], buffer, out uint bytesReturned, null)) - { - uint reparseTag = MemoryMarshal.Read(buffer); - short subsNameOffset = MemoryMarshal.Read(buffer.AsSpan(8)); - short subsNameLength = MemoryMarshal.Read(buffer.AsSpan(10)); - short printNameOffset = MemoryMarshal.Read(buffer.AsSpan(12)); - short printNameLength = MemoryMarshal.Read(buffer.AsSpan(14)); - string pathBuffer = Encoding.Unicode.GetString(buffer, 20, (int)bytesReturned - 20); - var subsString = pathBuffer.Substring(subsNameOffset / 2, subsNameLength / 2); - var printString = pathBuffer.Substring(printNameOffset / 2, printNameLength / 2); - var normalisedTarget = printString ?? subsString; - if (string.IsNullOrEmpty(normalisedTarget)) - { - normalisedTarget = subsString; - if (normalisedTarget.StartsWith(@"\??\", StringComparison.Ordinal)) - { - normalisedTarget = normalisedTarget.Substring(4); - } - } - if (reparseTag == PInvoke.IO_REPARSE_TAG_SYMLINK && (normalisedTarget.Length < 2 || normalisedTarget[1] != ':')) - { - // Target is relative, get the absolute path - normalisedTarget = normalisedTarget.TrimStart(Path.DirectorySeparatorChar); - path = path.TrimEnd(Path.DirectorySeparatorChar); - normalisedTarget = Path.GetFullPath(Path.Combine(path.Substring(0, path.LastIndexOf(Path.DirectorySeparatorChar)), normalisedTarget)); - } - return normalisedTarget; - } - } - return null; - } - - // https://stackoverflow.com/a/7988352 - public static unsafe IEnumerable<(string Name, long Size)> GetAlternateStreams(string path) - { - var streams = new List<(string Name, long Size)>(); - WIN32_FIND_STREAM_DATA findStreamData = default; - using FindCloseSafeHandle hFile = PInvoke.FindFirstStream(path, STREAM_INFO_LEVELS.FindStreamInfoStandard, &findStreamData); - - if (!hFile.IsInvalid) - { - do - { - // The documentation for FindFirstStreamW says that it is always a ::$DATA - // stream type, but FindNextStreamW doesn't guarantee that for subsequent - // streams so we check to make sure - var streamName = findStreamData.cStreamName.ToString(); - if (streamName.EndsWith(":$DATA") && streamName != "::$DATA") - streams.Add((streamName, findStreamData.StreamSize)); - } - while (PInvoke.FindNextStream(hFile, &findStreamData)); - } - - return streams; - } - - public static unsafe bool GetWin32FindDataForPath(string targetPath, out WIN32_FIND_DATAW findData) - { - fixed (WIN32_FIND_DATAW* findDataPointer = &findData) - { - using FindCloseSafeHandle hFile = PInvoke.FindFirstFileEx( - targetPath, - FINDEX_INFO_LEVELS.FindExInfoBasic, - findDataPointer, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - return !hFile.IsInvalid; - } - } - - private static string? GetPackageFamilyNameFromAppRegistryName(string appRegistryName) - { - using var appXKey = Registry.ClassesRoot.OpenSubKey(appRegistryName + @"\Application"); - var appUserModelIdObj = appXKey?.GetValue("AppUserModelId"); - string? appUserModelId = appUserModelIdObj?.ToString(); - string? packageFamilyName = null; - if (!string.IsNullOrEmpty(appUserModelId)) - { - int bangIndex = appUserModelId.IndexOf('!'); - packageFamilyName = bangIndex > 0 ? appUserModelId[..bangIndex] : appUserModelId; - } - - return packageFamilyName; - } - - private static string? GetUserChoiceFileAssociation(string filename) - { - var fileExtension = Path.GetExtension(filename); - if (string.IsNullOrEmpty(filename)) - return null; - - try - { - // Get ProgId from UserChoice - using var userChoiceKey = Registry.CurrentUser.OpenSubKey($@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{fileExtension}\UserChoice"); - var progIdObj = userChoiceKey?.GetValue("ProgId"); - string? progId = progIdObj?.ToString(); - - if (string.IsNullOrEmpty(progId)) - return null; - - // Get the package family name if it's an AppX app - if (progId.StartsWith("AppX", StringComparison.OrdinalIgnoreCase)) - { - string? packageFamilyName = GetPackageFamilyNameFromAppRegistryName(progId); - if (!string.IsNullOrEmpty(packageFamilyName)) - return packageFamilyName; - } - - // Find the open command for the ProgId - using var commandKey = Registry.ClassesRoot.OpenSubKey($@"{progId}\shell\open\command"); - var command = commandKey?.GetValue(null)?.ToString(); - - if (string.IsNullOrEmpty(command)) - return null; - - // Extract executable path from command string (e.g. "\"C:\\Program Files\\App\\app.exe\" \"%1\"") - var exePath = command.Trim(); - if (exePath.StartsWith("\"")) - { - int endQuote = exePath.IndexOf('\"', 1); - if (endQuote > 1) - exePath = exePath.Substring(1, endQuote - 1); - } - else - { - int firstSpace = exePath.IndexOf(' '); - if (firstSpace > 0) - exePath = exePath.Substring(0, firstSpace); - } - - return File.Exists(exePath) ? exePath : null; - } - catch - { - return null; - } - } - - private static async Task GetFileAssociationAsync(string filename, bool checkDesktopFirst = true) - { - // Find UWP apps - async Task GetUwpAssoc() - { - var uwpApps = await Launcher.FindFileHandlersAsync(Path.GetExtension(filename)); - return uwpApps.Any() ? uwpApps[0].PackageFamilyName : null; - } - - // Find desktop apps - unsafe string? GetDesktopAssoc() - { - Span result = stackalloc char[2048]; - fixed (char* fileNamePointer = filename, resultPointer = result) - { - var hResult = PInvoke.FindExecutable(fileNamePointer, null, resultPointer); - int length = result.IndexOf('\0'); - return (nint)(IntPtr)hResult > 32 ? result[..(length < 0 ? result.Length : length)].ToString() : null; - } - } - - if (checkDesktopFirst) - return GetDesktopAssoc() ?? await GetUwpAssoc(); - - return await GetUwpAssoc() ?? GetDesktopAssoc(); - } - } -} diff --git a/src/Files.App/Helpers/Win32/Win32Helper.WindowManagement.cs b/src/Files.App/Helpers/Win32/Win32Helper.WindowManagement.cs deleted file mode 100644 index 95ae1faabfae..000000000000 --- a/src/Files.App/Helpers/Win32/Win32Helper.WindowManagement.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Helpers -{ - /// - /// Provides static helper for Win32. - /// - public static partial class Win32Helper - { - /// - /// Brings the app window to foreground. - /// - /// - /// For more information, visit - ///
- /// -
- ///
- /// -
- /// - /// The window handle to bring. - public static unsafe void BringToForegroundEx(Windows.Win32.Foundation.HWND hWnd) - { - // LINUX-TODO(window): X11/Wayland activation is done through Window.Activate() - if (!OperatingSystem.IsWindows()) - return; - - var hCurWnd = PInvoke.GetForegroundWindow(); - - // Nothing to do if we already are the foreground window. Running the rest - // unconditionally calls SetFocus(hWnd) on the top-level HWND, which drops - // XAML focus to the window root and breaks arrow-key navigation after a - // click on a non-name column of a selected Details-layout row. - if (hCurWnd == hWnd) - return; - - var dwMyID = PInvoke.GetCurrentThreadId(); - var dwCurID = PInvoke.GetWindowThreadProcessId(hCurWnd); - - PInvoke.AttachThreadInput(dwCurID, dwMyID, true); - - PInvoke.SetWindowPos(hWnd, (Windows.Win32.Foundation.HWND)(-1), 0, 0, 0, 0, SET_WINDOW_POS_FLAGS.SWP_NOSIZE | SET_WINDOW_POS_FLAGS.SWP_NOMOVE); - PInvoke.SetWindowPos(hWnd, (Windows.Win32.Foundation.HWND)(-2), 0, 0, 0, 0, SET_WINDOW_POS_FLAGS.SWP_SHOWWINDOW | SET_WINDOW_POS_FLAGS.SWP_NOSIZE | SET_WINDOW_POS_FLAGS.SWP_NOMOVE); - PInvoke.SetForegroundWindow(hWnd); - PInvoke.SetFocus(hWnd); - PInvoke.SetActiveWindow(hWnd); - PInvoke.AttachThreadInput(dwCurID, dwMyID, false); - } - - /// - /// Force window to stay at bottom of other upper windows. - /// - /// The lParam of the message. - public static void ForceWindowPosition(nint lParam) - { - var windowPos = Marshal.PtrToStructure(lParam); - windowPos.flags |= SET_WINDOW_POS_FLAGS.SWP_NOZORDER; - Marshal.StructureToPtr(windowPos, lParam, false); - } - - /// - /// Applies the WS_EX_LAYOUTRTL extended style so the window's non-client area is mirrored. - /// - /// The window handle. - public static void EnableRtlLayout(nint hWnd) - { - var hwnd = new Windows.Win32.Foundation.HWND(hWnd); - var exStyle = PInvoke.GetWindowLongPtr(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE); - PInvoke.SetWindowLongPtr(hwnd, WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, exStyle | (nint)WINDOW_EX_STYLE.WS_EX_LAYOUTRTL); - } - } -} diff --git a/src/Files.App/Helpers/Win32/Win32PInvoke.Consts.cs b/src/Files.App/Helpers/Win32/Win32PInvoke.Consts.cs deleted file mode 100644 index 0e1d2ecb0338..000000000000 --- a/src/Files.App/Helpers/Win32/Win32PInvoke.Consts.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -namespace Files.App.Helpers -{ - public static partial class Win32PInvoke - { - public static readonly Guid DataTransferManagerInteropIID = - new(0xa5caee9b, 0x8708, 0x49d1, 0x8d, 0x36, 0x67, 0xd2, 0x5a, 0x8d, 0xa0, 0x0c); - - public const int FILE_NOTIFY_CHANGE_FILE_NAME = 1; - public const int FILE_NOTIFY_CHANGE_DIR_NAME = 2; - public const int FILE_NOTIFY_CHANGE_ATTRIBUTES = 4; - public const int FILE_NOTIFY_CHANGE_SIZE = 8; - public const int FILE_NOTIFY_CHANGE_LAST_WRITE = 16; - public const int FILE_NOTIFY_CHANGE_LAST_ACCESS = 32; - public const int FILE_NOTIFY_CHANGE_CREATION = 64; - public const int FILE_NOTIFY_CHANGE_SECURITY = 256; - - public const int INVALID_HANDLE_VALUE = -1; - public const int FILE_SHARE_READ = 0x00000001; - public const int FILE_SHARE_WRITE = 0x00000002; - public const uint FILE_SHARE_DELETE = 0x00000004; - public const int OPEN_EXISTING = 3; - public const int IOCTL_STORAGE_EJECT_MEDIA = 0x2D4808; - public const int IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804; - - public const uint FILE_APPEND_DATA = 0x0004; - - public const int MNC_CLOSE = 1; - - public const uint FILE_BEGIN = 0; - public const uint FILE_END = 2; - - public const uint CREATE_ALWAYS = 2; - public const uint CREATE_NEW = 1; - public const uint OPEN_ALWAYS = 4; - public const uint TRUNCATE_EXISTING = 5; - - // FSCTL - public const int FSCTL_GET_REPARSE_POINT = 0x000900A8; - - public const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024; - public const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003; - public const uint IO_REPARSE_TAG_SYMLINK = 0xA000000C; - - public const int FIND_FIRST_EX_CASE_SENSITIVE = 1; - public const int FIND_FIRST_EX_LARGE_FETCH = 2; - - public const int NORM_IGNORECASE = 0x00000001; - public const int NORM_IGNORENONSPACE = 0x00000002; - public const int NORM_IGNORESYMBOLS = 0x00000004; - public const int LINGUISTIC_IGNORECASE = 0x00000010; - public const int LINGUISTIC_IGNOREDIACRITIC = 0x00000020; - public const int NORM_IGNOREKANATYPE = 0x00010000; - public const int NORM_IGNOREWIDTH = 0x00020000; - public const int NORM_LINGUISTIC_CASING = 0x08000000; - public const int SORT_STRINGSORT = 0x00001000; - public const int SORT_DIGITSASNUMBERS = 0x00000008; - - public const string LOCALE_NAME_USER_DEFAULT = null; - public const string LOCALE_NAME_INVARIANT = ""; - public const string LOCALE_NAME_SYSTEM_DEFAULT = "!sys-default-locale"; - } -} diff --git a/src/Files.App/Helpers/Win32/Win32PInvoke.Enums.cs b/src/Files.App/Helpers/Win32/Win32PInvoke.Enums.cs deleted file mode 100644 index b545d9be4cc8..000000000000 --- a/src/Files.App/Helpers/Win32/Win32PInvoke.Enums.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -namespace Files.App.Helpers -{ - public static partial class Win32PInvoke - { - public enum File_Attributes : uint - { - Readonly = 0x00000001, - Hidden = 0x00000002, - System = 0x00000004, - Directory = 0x00000010, - Archive = 0x00000020, - Device = 0x00000040, - Normal = 0x00000080, - Temporary = 0x00000100, - SparseFile = 0x00000200, - ReparsePoint = 0x00000400, - Compressed = 0x00000800, - Offline = 0x00001000, - NotContentIndexed = 0x00002000, - Encrypted = 0x00004000, - Write_Through = 0x80000000, - Overlapped = 0x40000000, - NoBuffering = 0x20000000, - RandomAccess = 0x10000000, - SequentialScan = 0x08000000, - DeleteOnClose = 0x04000000, - BackupSemantics = 0x02000000, - PosixSemantics = 0x01000000, - OpenReparsePoint = 0x00200000, - OpenNoRecall = 0x00100000, - FirstPipeInstance = 0x00080000 - } - - public enum FILE_INFO_BY_HANDLE_CLASS - { - FileBasicInfo = 0, - FileStandardInfo = 1, - FileNameInfo = 2, - FileRenameInfo = 3, - FileDispositionInfo = 4, - FileAllocationInfo = 5, - FileEndOfFileInfo = 6, - FileStreamInfo = 7, - FileCompressionInfo = 8, - FileAttributeTagInfo = 9, - FileIdBothDirectoryInfo = 10,// 0x0A - FileIdBothDirectoryRestartInfo = 11, // 0xB - FileIoPriorityHintInfo = 12, // 0xC - FileRemoteProtocolInfo = 13, // 0xD - FileFullDirectoryInfo = 14, // 0xE - FileFullDirectoryRestartInfo = 15, // 0xF - FileStorageInfo = 16, // 0x10 - FileAlignmentInfo = 17, // 0x11 - FileIdInfo = 18, // 0x12 - FileIdExtdDirectoryInfo = 19, // 0x13 - FileIdExtdDirectoryRestartInfo = 20, // 0x14 - MaximumFileInfoByHandlesClass - } - - public enum GET_FILEEX_INFO_LEVELS - { - GetFileExInfoStandard, - } - - public enum StreamInfoLevels - { - FindStreamInfoStandard = 0 - } - - public enum FINDEX_INFO_LEVELS - { - FindExInfoStandard = 0, - FindExInfoBasic = 1 - } - - public enum FINDEX_SEARCH_OPS - { - FindExSearchNameMatch = 0, - FindExSearchLimitToDirectories = 1, - FindExSearchLimitToDevices = 2 - } - - [Flags] - public enum ClassContext : uint - { - LocalServer = 0x4 - } - } -} diff --git a/src/Files.App/Helpers/Win32/Win32PInvoke.Methods.cs b/src/Files.App/Helpers/Win32/Win32PInvoke.Methods.cs deleted file mode 100644 index 7bcbb12f785a..000000000000 --- a/src/Files.App/Helpers/Win32/Win32PInvoke.Methods.cs +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using Microsoft.Win32.SafeHandles; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; - -namespace Files.App.Helpers -{ - public static partial class Win32PInvoke - { - public sealed partial class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid - { - internal SafeFindHandle(IntPtr handle) : base(true) - { - SetHandle(handle); - } - - protected override bool ReleaseHandle() => FindClose(handle); - } - - public delegate void LpoverlappedCompletionRoutine( - uint dwErrorCode, - uint dwNumberOfBytesTransfered, - OVERLAPPED lpOverlapped - ); - - public delegate void LPOVERLAPPED_COMPLETION_ROUTINE( - uint dwErrorCode, - uint dwNumberOfBytesTransfered, - ref NativeOverlapped lpOverlapped - ); - - [DllImport("api-ms-win-core-handle-l1-1-0.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool CloseHandle( - IntPtr hObject - ); - - [DllImport("api-ms-win-core-io-l1-1-1.dll")] - public static extern bool CancelIoEx( - IntPtr hFile, - IntPtr lpOverlapped - ); - - [DllImport("api-ms-win-core-synch-l1-2-0.dll", SetLastError = true)] - public static extern uint WaitForSingleObjectEx( - IntPtr hHandle, - uint dwMilliseconds, - bool bAlertable - ); - - [DllImport("api-ms-win-core-file-l2-1-0.dll", SetLastError = true, CharSet = CharSet.Unicode)] - public unsafe static extern bool ReadDirectoryChangesW( - IntPtr hDirectory, - byte* lpBuffer, - int nBufferLength, - bool bWatchSubtree, - int dwNotifyFilter, - int* lpBytesReturned, - ref OVERLAPPED lpOverlapped, - LpoverlappedCompletionRoutine lpCompletionRoutine - ); - - [DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", SetLastError = true, CharSet = CharSet.Auto)] - public static extern IntPtr CreateFileFromAppW( - string lpFileName, - uint dwDesiredAccess, - uint dwShareMode, - IntPtr SecurityAttributes, - uint dwCreationDisposition, - uint dwFlagsAndAttributes, - IntPtr hTemplateFile - ); - - [DllImport("api-ms-win-core-io-l1-1-0.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)] - public static extern bool DeviceIoControl( - IntPtr hDevice, - uint dwIoControlCode, - IntPtr lpInBuffer, - uint nInBufferSize, - IntPtr lpOutBuffer, - uint nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped - ); - - [DllImport("api-ms-win-core-io-l1-1-0.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)] - public static extern bool DeviceIoControl( - IntPtr hDevice, - uint dwIoControlCode, - byte[] lpInBuffer, - uint nInBufferSize, - IntPtr lpOutBuffer, - uint nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped - ); - - [DllImport("api-ms-win-core-io-l1-1-0.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool DeviceIoControl( - IntPtr hDevice, - uint dwIoControlCode, - IntPtr lpInBuffer, - uint nInBufferSize, - //IntPtr lpOutBuffer, - out REPARSE_DATA_BUFFER outBuffer, - uint nOutBufferSize, - out uint lpBytesReturned, - IntPtr lpOverlapped); - - [DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern IntPtr CreateFileFromApp( - string? lpFileName, - uint dwDesiredAccess, - uint dwShareMode, - IntPtr SecurityAttributes, - uint dwCreationDisposition, - uint dwFlagsAndAttributes, - IntPtr hTemplateFile - ); - - [DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", SetLastError = true, CharSet = CharSet.Auto)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool GetFileAttributesExFromApp( - string lpFileName, - GET_FILEEX_INFO_LEVELS fInfoLevelId, - out WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); - - [DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", SetLastError = true, CharSet = CharSet.Auto)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool SetFileAttributesFromApp( - string lpFileName, - FileAttributes dwFileAttributes); - - [DllImport("api-ms-win-core-file-l1-2-1.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public unsafe static extern bool ReadFile( - IntPtr hFile, - byte* lpBuffer, - int nBufferLength, - int* lpBytesReturned, - IntPtr lpOverlapped - ); - - [DllImport("api-ms-win-core-file-l1-2-1.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public unsafe static extern bool WriteFile( - IntPtr hFile, - byte* lpBuffer, - int nBufferLength, - int* lpBytesWritten, - IntPtr lpOverlapped - ); - - [DllImport("api-ms-win-core-file-l1-2-1.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern bool WriteFileEx( - IntPtr hFile, - byte[] lpBuffer, - uint nNumberOfBytesToWrite, - [In] ref NativeOverlapped lpOverlapped, - LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine); - - [DllImport("api-ms-win-core-file-l1-2-1.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern bool GetFileTime( - [In] IntPtr hFile, - out System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime, - out System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime, - out System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime - ); - - [DllImport("api-ms-win-core-file-l1-2-1.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern bool SetFileTime( - [In] IntPtr hFile, - in System.Runtime.InteropServices.ComTypes.FILETIME lpCreationTime, - in System.Runtime.InteropServices.ComTypes.FILETIME lpLastAccessTime, - in System.Runtime.InteropServices.ComTypes.FILETIME lpLastWriteTime - ); - - [DllImport("api-ms-win-core-file-l2-1-1.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)] - public static extern bool GetFileInformationByHandleEx( - IntPtr hFile, - FILE_INFO_BY_HANDLE_CLASS infoClass, - out FILE_ID_BOTH_DIR_INFO dirInfo, - uint dwBufferSize - ); - - [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] - public static extern IntPtr FindFirstStreamW( - string lpFileName, - StreamInfoLevels InfoLevel, - [In, Out, MarshalAs(UnmanagedType.LPStruct)] WIN32_FIND_STREAM_DATA lpFindStreamData, - uint dwFlags - ); - - [DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Auto, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool FindNextStreamW( - IntPtr hndFindFile, - [In, Out, MarshalAs(UnmanagedType.LPStruct)] WIN32_FIND_STREAM_DATA lpFindStreamData - ); - - [DllImport("api-ms-win-core-wow64-l1-1-1.dll", SetLastError = true)] - public static extern bool IsWow64Process2( - IntPtr process, - out ushort processMachine, - out ushort nativeMachine - ); - - [DllImport("api-ms-win-core-file-l1-1-0.dll", CharSet = CharSet.Unicode)] - public static extern bool FindNextFile( - IntPtr hFindFile, - out WIN32_FIND_DATA lpFindFileData - ); - - [DllImport("api-ms-win-core-file-l1-1-0.dll")] - public static extern bool FindClose( - IntPtr hFindFile - ); - - [DllImport("api-ms-win-core-timezone-l1-1-0.dll", SetLastError = true)] - public static extern bool FileTimeToSystemTime( - in System.Runtime.InteropServices.ComTypes.FILETIME lpFileTime, - out SYSTEMTIME lpSystemTime - ); - - [DllImport("api-ms-win-core-file-fromapp-l1-1-0.dll", SetLastError = true, CharSet = CharSet.Unicode)] - public static extern IntPtr FindFirstFileExFromApp( - string lpFileName, - FINDEX_INFO_LEVELS fInfoLevelId, - out WIN32_FIND_DATA lpFindFileData, - FINDEX_SEARCH_OPS fSearchOp, - IntPtr lpSearchFilter, - int dwAdditionalFlags - ); - - public static SafeFindHandle FindFirstFileExFromAppSafe( - string lpFileName, - FINDEX_INFO_LEVELS fInfoLevelId, - out WIN32_FIND_DATA lpFindFileData, - FINDEX_SEARCH_OPS fSearchOp, - IntPtr lpSearchFilter, - int dwAdditionalFlags - ) - { - var handle = FindFirstFileExFromApp( - lpFileName, - fInfoLevelId, - out lpFindFileData, - fSearchOp, - lpSearchFilter, - dwAdditionalFlags); - - return new(handle); - } - - [LibraryImport("shell32.dll", EntryPoint = "#865", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - public static partial bool IsElevationRequired( - [MarshalAs(UnmanagedType.LPWStr)] string pszPath); - - // cryptui.dll - [DllImport("cryptui.dll", SetLastError = true, CharSet = CharSet.Auto)] - public unsafe static extern bool CryptUIDlgViewSignerInfo(CRYPTUI_VIEWSIGNERINFO_STRUCT* pViewInfo); - } -} diff --git a/src/Files.App/Helpers/Win32/Win32PInvoke.Structs.cs b/src/Files.App/Helpers/Win32/Win32PInvoke.Structs.cs deleted file mode 100644 index e3d19a8c4c8b..000000000000 --- a/src/Files.App/Helpers/Win32/Win32PInvoke.Structs.cs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2024 Files Community -// Licensed under the MIT License. See the LICENSE. - -using System.IO; -using System.Runtime.InteropServices; -using Windows.Win32.Foundation; -using Windows.Win32.Security.Cryptography; - -namespace Files.App.Helpers -{ - public static partial class Win32PInvoke - { - public unsafe struct OVERLAPPED - { - public IntPtr Internal; - public IntPtr InternalHigh; - public Union PointerAndOffset; - public IntPtr hEvent; - - [StructLayout(LayoutKind.Explicit)] - public struct Union - { - [FieldOffset(0)] public void* IntPtr; - [FieldOffset(0)] public OffsetPair Offset; - - public struct OffsetPair { public uint Offset; public uint OffsetHigh; } - } - } - - public unsafe struct FILE_NOTIFY_INFORMATION - { - public uint NextEntryOffset; - public uint Action; - public uint FileNameLength; - public fixed char FileName[1]; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct REPARSE_DATA_BUFFER - { - public uint ReparseTag; - public short ReparseDataLength; - public short Reserved; - public short SubsNameOffset; - public short SubsNameLength; - public short PrintNameOffset; - public short PrintNameLength; - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAXIMUM_REPARSE_DATA_BUFFER_SIZE)] - public char[] PathBuffer; - } - - [StructLayout(LayoutKind.Sequential)] - public struct WIN32_FILE_ATTRIBUTE_DATA - { - public FileAttributes dwFileAttributes; - public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; - public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; - public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; - public uint nFileSizeHigh; - public uint nFileSizeLow; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public struct FILE_ID_BOTH_DIR_INFO - { - public uint NextEntryOffset; - public uint FileIndex; - public long CreationTime; - public long LastAccessTime; - public long LastWriteTime; - public long ChangeTime; - public long EndOfFile; - public long AllocationSize; - public uint FileAttributes; - public uint FileNameLength; - public uint EaSize; - public char ShortNameLength; - [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 12)] - public string ShortName; - public long FileId; - [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 1)] - public string FileName; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 8)] - public struct FILE_STREAM_INFO - { - public uint NextEntryOffset; - public uint StreamNameLength; - public long StreamSize; - public long StreamAllocationSize; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] - public string StreamName; - } - - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - public sealed class WIN32_FIND_STREAM_DATA - { - public long StreamSize; - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 296)] - public string? cStreamName; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SID_AND_ATTRIBUTES - { - public IntPtr Sid; - - public uint Attributes; - } - - [StructLayout(LayoutKind.Sequential)] - public struct SYSTEMTIME - { - [MarshalAs(UnmanagedType.U2)] public short Year; - [MarshalAs(UnmanagedType.U2)] public short Month; - [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; - [MarshalAs(UnmanagedType.U2)] public short Day; - [MarshalAs(UnmanagedType.U2)] public short Hour; - [MarshalAs(UnmanagedType.U2)] public short Minute; - [MarshalAs(UnmanagedType.U2)] public short Second; - [MarshalAs(UnmanagedType.U2)] public short Milliseconds; - - public SYSTEMTIME(DateTime dt) - { - dt = dt.ToUniversalTime(); // SetSystemTime expects the SYSTEMTIME in UTC - Year = (short)dt.Year; - Month = (short)dt.Month; - DayOfWeek = (short)dt.DayOfWeek; - Day = (short)dt.Day; - Hour = (short)dt.Hour; - Minute = (short)dt.Minute; - Second = (short)dt.Second; - Milliseconds = (short)dt.Millisecond; - } - - public DateTime ToDateTime() - { - return new(Year, Month, Day, Hour, Minute, Second, Milliseconds, DateTimeKind.Utc); - } - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public struct WIN32_FIND_DATA - { - public uint dwFileAttributes; - - public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; - public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; - public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; - - public uint nFileSizeHigh; - public uint nFileSizeLow; - public uint dwReserved0; - public uint dwReserved1; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string cFileName; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] - public string cAlternateFileName; - } - - [StructLayout(LayoutKind.Sequential)] - public unsafe struct SignDataHandle - { - public uint dwObjSize; - public CMSG_SIGNER_INFO* pSignerInfo; - public HCERTSTORE hCertStoreHandle; - } - - [StructLayout(LayoutKind.Sequential)] - public unsafe struct CRYPTOAPI_BLOB - { - public uint cbData; - public void* pbData; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] - public unsafe struct CRYPTUI_VIEWSIGNERINFO_STRUCT - { - public uint dwSize; - public HWND hwndParent; - public uint dwFlags; - public PCSTR szTitle; - public CMSG_SIGNER_INFO* pSignerInfo; - public void* hMsg; - public PCSTR pszOID; - public uint? dwReserved; - public uint cStores; - public HCERTSTORE* rghStores; - public uint cPropPages; - public void* rgPropPages; - } - } -} diff --git a/src/Files.App/MainWindow.Linux.cs b/src/Files.App/MainWindow.Linux.cs index f62b7f14c05a..42cfd40d453c 100644 --- a/src/Files.App/MainWindow.Linux.cs +++ b/src/Files.App/MainWindow.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions; using Files.Platform.Abstractions.Appearance; using Microsoft.UI; @@ -126,4 +125,3 @@ public void UpdateLinuxChromeRegions(int dragStart, int titleHeight) } } } -#endif diff --git a/src/Files.App/MainWindow.xaml.cs b/src/Files.App/MainWindow.xaml.cs index 3cbfe89803e8..459b1832a040 100644 --- a/src/Files.App/MainWindow.xaml.cs +++ b/src/Files.App/MainWindow.xaml.cs @@ -13,9 +13,6 @@ using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Storage; -#if WINDOWS -using Windows.Win32.Foundation; -#endif using WinRT; using IO = System.IO; @@ -36,15 +33,9 @@ public MainWindow() : base(416, 316) { InitializeComponent(); -#if WINDOWS - ExtendsContentIntoTitleBar = true; -#else ExtendsContentIntoTitleBar = UseClientSideDecorations; -#endif Title = OperatingSystem.IsLinux() ? Strings.LinuxAppDisplayName.GetLocalizedResource() : "Files"; -#if !WINDOWS Title = FormatRootModeTitle(Title); -#endif AppWindow.TitleBar.ButtonBackgroundColor = Colors.Transparent; AppWindow.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent; AppWindow.TitleBar.ButtonPressedBackgroundColor = Colors.Transparent; @@ -271,10 +262,6 @@ public async Task InitializeApplicationAsync(object? activatedEventArgs) BringToForeground(); } -#if WINDOWS - if (Windows.Win32.PInvoke.IsIconic(new(WindowHandle)) && appWindow?.Presenter is OverlappedPresenter overlapped) - overlapped.Restore(); -#endif } private async Task EnsureContentHasKeyboardFocusAsync() @@ -456,11 +443,7 @@ async Task PerformNavigationAsync(string? payload, string? selectItem = null) private void BringToForeground() { -#if WINDOWS - Win32Helper.BringToForegroundEx(new(WindowHandle)); -#else Activate(); -#endif } public bool SetCanWindowToFront(bool canWindowToFront) @@ -476,22 +459,5 @@ public bool SetCanWindowToFront(bool canWindowToFront) } } -#if WINDOWS - protected override bool OnWindowMessageReceived(uint message, WPARAM wParam, LPARAM lParam, ref LRESULT result) - { - if ((!CanWindowToFront) && message == Windows.Win32.PInvoke.WM_WINDOWPOSCHANGING) - { - Win32Helper.ForceWindowPosition(lParam.Value); - return true; - } - else if (message == Windows.Win32.PInvoke.WM_MENUCHAR && (wParam.Value & 0xFFFF) == '\r') - { - result = new(Win32PInvoke.MNC_CLOSE << 16); - return true; - } - - return false; - } -#endif } } diff --git a/src/Files.App/Program.cs b/src/Files.App/Program.cs deleted file mode 100644 index 6014693757fd..000000000000 --- a/src/Files.App/Program.cs +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using Microsoft.UI.Dispatching; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Settings; -using Microsoft.Windows.AppLifecycle; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using Windows.Win32.UI.WindowsAndMessaging; -using Windows.ApplicationModel.Activation; -using Windows.Storage; - -namespace Files.App -{ - /// - /// Represents the base entry point of the Files app. - /// - /// - /// Gets called at the first time when the app launched or activated. - /// - internal sealed class Program - { - public static Semaphore? Pool { get; set; } - - private const string LaunchCwdKey = "LastLaunchCwd"; - - /// - /// Reads and clears the working directory captured by the source process - /// in , falling back to the current process's working - /// directory if no value is pending. (#16982) - /// - public static string ConsumeLaunchCwd() - { - var values = ApplicationData.Current.LocalSettings.Values; - var cwd = values.TryGetValue(LaunchCwdKey, out var raw) ? raw as string : null; - if (cwd is not null) - values.Remove(LaunchCwdKey); - return string.IsNullOrEmpty(cwd) ? Environment.CurrentDirectory : cwd; - } - - static Program() - { - // Capture the source process's working directory before any potential - // activation redirect, so a receiving instance can resolve relative - // paths like "." against the terminal's CWD rather than its own. (#16982) - ApplicationData.Current.LocalSettings.Values[LaunchCwdKey] = Environment.CurrentDirectory; - - var pool = new Semaphore(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance", out var isNew); - - if (!isNew) - { - var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1); - var instance = AppInstance.FindOrRegisterForKey(activePid.ToString()); - - // A stale key resolves to this process itself; redirecting to self would drop the activation - if (!instance.IsCurrent) - { - // Resume cached instance - pool.Release(); - - // Redirect to the main process - RedirectActivationTo(instance, AppInstance.GetCurrent().GetActivatedEventArgs()); - - // Kill the current process - Environment.Exit(0); - } - } - - pool.Dispose(); - } - - /// - /// Initializes the process; the entry point of the process. - /// - /// - /// cannot be declared to be async because this prevents Narrator from reading XAML elements in a WinUI app. - /// - [STAThread] - private static void Main() - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - WinRT.ComWrappersSupport.InitializeComWrappers(); - - // We are about to do the first WinRT server call, in case the WinRT server is hanging - // we need to kill the server if there are no other Files instances already running - - static bool ProcessPathPredicate(Process p) - { - try - { - return p.MainModule?.FileName - .StartsWith(Windows.ApplicationModel.Package.Current.EffectivePath, StringComparison.OrdinalIgnoreCase) ?? false; - } - catch - { - return false; - } - } - - // Off the startup path: MainModule reads cost tens of milliseconds per scanned process - _ = Task.Run(static () => - { - var processes = Process.GetProcessesByName("Files") - .Where(ProcessPathPredicate) - .Where(p => p.Id != Environment.ProcessId); - - if (!processes.Any()) - { - foreach (var process in Process.GetProcessesByName("Files.App.Server").Where(ProcessPathPredicate)) - { - try - { - process.Kill(); - } - catch - { - // ignore any exceptions - } - finally - { - process.Dispose(); - } - } - } - }); - - // NOTE: - // This has been commented out since out-of-proc WinRT server seems not to support elevation. - // For more info, see the GitHub issue (#15384). - // Now we can do the first WinRT server call - //Server.AppInstanceMonitor.StartMonitor(Environment.ProcessId); - - var OpenTabInExistingInstance = ApplicationData.Current.LocalSettings.Values.Get("OpenTabInExistingInstance", true); - - AppActivationArguments activatedArgs; - try - { - activatedArgs = AppInstance.GetCurrent().GetActivatedEventArgs(); - } - catch (COMException ex) when (ex.HResult == unchecked((int)0x80040154)) - { - Windows.Win32.PInvoke.MessageBox( - default, - Constants.Startup.MissingRuntimeMessage, - Constants.Startup.MissingRuntimeTitle, - MESSAGEBOX_STYLE.MB_ICONERROR); - - throw new InvalidOperationException(Constants.Startup.MissingRuntimeMessage, ex); - } - - var commandLineArgs = GetCommandLineArgs(activatedArgs); - - if (commandLineArgs is not null) - { - var parsedCommands = CommandLineParser.ParseUntrustedCommands(commandLineArgs); - - if (parsedCommands is not null) - { - foreach (var command in parsedCommands) - { - switch (command.Type) - { - case ParsedCommandType.ExplorerShellCommand: - if (!ShellHelpers.IsSupportedShellPath(command.Payload)) - { - OpenShellCommandInExplorer(command.Payload, Environment.ProcessId); - return; - } - break; - - default: - break; - } - } - } - - // Always open a new instance for OpenDialog, never open new instance for "-Tag" command - if (parsedCommands is null || !parsedCommands.Any(x => x.Type == ParsedCommandType.OutputPath) && - (OpenTabInExistingInstance || parsedCommands.Any(x => x.Type == ParsedCommandType.TagFiles))) - { - var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1); - var instance = AppInstance.FindOrRegisterForKey(activePid.ToString()); - - if (!instance.IsCurrent) - { - RedirectActivationTo(instance, activatedArgs); - return; - } - } - } - else if (activatedArgs.Data is ILaunchActivatedEventArgs tileArgs) - { - if (tileArgs.Arguments is not null && - FileExtensionHelpers.IsExecutableFile(tileArgs.Arguments)) - { - if (File.Exists(tileArgs.Arguments)) - { - OpenFileFromTile(tileArgs.Arguments); - return; - } - } - } - - if (OpenTabInExistingInstance && commandLineArgs is null) - { - if (activatedArgs.Data is ILaunchActivatedEventArgs launchArgs) - { - var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1); - var instance = AppInstance.FindOrRegisterForKey(activePid.ToString()); - if (!instance.IsCurrent && !string.IsNullOrWhiteSpace(launchArgs.Arguments)) - { - RedirectActivationTo(instance, activatedArgs); - return; - } - } - else if (activatedArgs.Data is IProtocolActivatedEventArgs protocolArgs) - { - var parsedArgs = protocolArgs.Uri.Query.TrimStart('?').Split('='); - if (parsedArgs.Length == 1) - { - var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1); - var instance = AppInstance.FindOrRegisterForKey(activePid.ToString()); - if (!instance.IsCurrent) - { - RedirectActivationTo(instance, activatedArgs); - return; - } - } - } - else if (activatedArgs.Data is IFileActivatedEventArgs) - { - var activePid = ApplicationData.Current.LocalSettings.Values.Get("INSTANCE_ACTIVE", -1); - var instance = AppInstance.FindOrRegisterForKey(activePid.ToString()); - if (!instance.IsCurrent) - { - RedirectActivationTo(instance, activatedArgs); - return; - } - } - } - - var currentInstance = AppInstance.FindOrRegisterForKey((-Environment.ProcessId).ToString()); - if (currentInstance.IsCurrent) - currentInstance.Activated += OnActivated; - - ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = -Environment.ProcessId; - - // Optional XAML performance changes must be opted into before XAML initialization - XamlOptionalChanges.EnableChange(XamlChangeId.DefaultStyleOptimizations); - XamlOptionalChanges.EnableChange(XamlChangeId.OptimizeApplyStyles); - XamlOptionalChanges.EnableChange(XamlChangeId.IconNoGridOptimization); - XamlOptionalChanges.EnableChange(XamlChangeId.DeferContextFlyoutInit); - - Application.Start((p) => - { - var context = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread()); - SynchronizationContext.SetSynchronizationContext(context); - - _ = new App(); - }); - } - - /// - /// Gets command line args from AppActivationArguments - /// Command line args can be ILaunchActivatedEventArgs, ICommandLineActivatedEventArgs or IProtocolActivatedEventArgs - /// - private static string? GetCommandLineArgs(AppActivationArguments activatedArgs) - { - // WINUI3: When launching from commandline the argument is not ICommandLineActivatedEventArgs (#10370) - var cmdLaunchArgs = activatedArgs.Data is ILaunchActivatedEventArgs launchArgs && - launchArgs.Arguments is not null && - CommandLineParser.SplitArguments(launchArgs.Arguments, true).FirstOrDefault() is string arg0 && - (arg0.EndsWith($"files-dev.exe", StringComparison.OrdinalIgnoreCase) || - arg0.EndsWith($"files-dev", StringComparison.OrdinalIgnoreCase)) ? launchArgs.Arguments : null; - var cmdProtocolArgs = activatedArgs.Data is IProtocolActivatedEventArgs protocolArgs && - protocolArgs.Uri.Query.TrimStart('?').Split('=') is string[] parsedArgs && - parsedArgs.Length == 2 && parsedArgs[0] == "cmd" ? Uri.UnescapeDataString(parsedArgs[1]) : null; - var cmdLineArgs = activatedArgs.Data is ICommandLineActivatedEventArgs cmdArgs ? cmdArgs.Operation.Arguments : null; - - return cmdLaunchArgs ?? cmdProtocolArgs ?? cmdLineArgs; - } - - /// - /// Gets invoked when the application is activated. - /// - private static async void OnActivated(object? sender, AppActivationArguments args) - { - // WINUI3: Verify if needed or OnLaunched is called - if (App.Current is App thisApp) - await thisApp.OnActivatedAsync(args); - } - - /// - /// Redirects the activation to the main process. - /// - /// - /// Redirects on another thread and uses a non-blocking wait method to wait for the redirection to complete. - /// - public static void RedirectActivationTo(AppInstance keyInstance, AppActivationArguments args) - { - keyInstance.RedirectActivationToAsync(args).AsTask().Wait(); - } - - public static void OpenShellCommandInExplorer(string shellCommand, int pid) - { - Win32Helper.OpenFolderInExistingShellWindow(shellCommand); - } - - public static void OpenFileFromTile(string filePath) - { - LaunchHelper.LaunchAppAsync(filePath, null, null).Wait(); - } - } -} diff --git a/src/Files.App/Services/App/AppUpdateSideloadService.cs b/src/Files.App/Services/App/AppUpdateSideloadService.cs deleted file mode 100644 index 7ce469893093..000000000000 --- a/src/Files.App/Services/App/AppUpdateSideloadService.cs +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.IO; -using System.Net.Http; -using System.Text; -using System.Xml.Linq; -using Windows.ApplicationModel; -using Windows.Management.Deployment; -using Windows.Storage; -using Windows.Win32; -using Windows.Win32.System.Recovery; - -namespace Files.App.Services -{ - public sealed partial class SideloadUpdateService : ObservableObject, IUpdateService, IDisposable - { - private const string SIDELOAD_STABLE = "https://cdn.files.community/files/stable/Files.Package.appinstaller"; - private const string SIDELOAD_PREVIEW = "https://cdn.files.community/files/preview/Files.Package.appinstaller"; - - private readonly HttpClient _client = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(3) }); - - private readonly Dictionary _sideloadVersion = new() - { - { "Files", SIDELOAD_STABLE }, - { "FilesPreview", SIDELOAD_PREVIEW } - }; - - private ILogger? Logger { get; } = Ioc.Default.GetRequiredService>(); - - private string PackageName { get; } = Package.Current.Id.Name; - - private Version PackageVersion { get; } = new( - Package.Current.Id.Version.Major, - Package.Current.Id.Version.Minor, - Package.Current.Id.Version.Build, - Package.Current.Id.Version.Revision); - - private bool _isUpdateAvailable; - public bool IsUpdateAvailable - { - get => _isUpdateAvailable; - private set => SetProperty(ref _isUpdateAvailable, value); - } - - private bool _isUpdating; - public bool IsUpdating - { - get => _isUpdating; - private set => SetProperty(ref _isUpdating, value); - } - - private int _updateProgress; - public int UpdateProgress - { - get => _updateProgress; - private set => SetProperty(ref _updateProgress, value); - } - - public bool IsAppUpdated - { - get => AppLifecycleHelper.IsAppUpdated; - } - - private bool _areReleaseNotesAvailable = false; - public bool AreReleaseNotesAvailable - { - get => _areReleaseNotesAvailable; - private set => SetProperty(ref _areReleaseNotesAvailable, value); - } - - public async Task DownloadUpdatesAsync() - { - await ApplyPackageUpdateAsync(); - } - - public Task DownloadMandatoryUpdatesAsync() - { - return Task.CompletedTask; - } - - public async Task CheckForUpdatesAsync() - { - IsUpdateAvailable = false; - try - { - Logger?.LogInformation($"SIDELOAD: Checking for updates..."); - - await using var stream = await _client.GetStreamAsync(_sideloadVersion[PackageName]); - - var appInstaller = await XDocument.LoadAsync(stream, LoadOptions.None, default); - var root = appInstaller.Root; - var mainBundle = root?.Element(root.Name.Namespace + "MainBundle"); - var remotePackageName = mainBundle?.Attribute("Name")?.Value; - var remoteVersionText = root?.Attribute("Version")?.Value; - if (string.IsNullOrWhiteSpace(remotePackageName) || string.IsNullOrWhiteSpace(remoteVersionText)) - { - throw new InvalidDataException("The app installer manifest does not identify a package and version."); - } - - var remoteVersion = new Version(remoteVersionText); - - Logger?.LogInformation($"SIDELOAD: Current Package Name: {PackageName}"); - Logger?.LogInformation($"SIDELOAD: Remote Package Name: {remotePackageName}"); - Logger?.LogInformation($"SIDELOAD: Current Version: {PackageVersion}"); - Logger?.LogInformation($"SIDELOAD: Remote Version: {remoteVersion}"); - - // Check details and version number - if (remotePackageName.Equals(PackageName) && remoteVersion.CompareTo(PackageVersion) > 0) - { - Logger?.LogInformation("SIDELOAD: Update found."); - MainWindow.Instance.DispatcherQueue.TryEnqueue(() => - { - IsUpdateAvailable = true; - }); - } - else - { - Logger?.LogWarning("SIDELOAD: Update not found."); - } - } - catch (HttpRequestException ex) - { - Logger?.LogDebug(ex, ex.Message); - } - catch (Exception ex) - { - Logger?.LogError(ex, ex.Message); - } - } - - public async Task CheckAndUpdateFilesLauncherAsync() - { - try - { - var destFolderPath = Path.Combine(UserDataPaths.GetDefault().LocalAppData, "Files"); - var destExeFilePath = Path.Combine(destFolderPath, "Files.App.Launcher.exe"); - var branchFilePath = Path.Combine(destFolderPath, "Branch.txt"); - - // If Files.App.Launcher.exe doesn't exist, no need to update it. - if (!File.Exists(destExeFilePath)) - return; - - // Check if the launcher file is associated with the current branch of the app. - if (File.Exists(branchFilePath)) - { - try - { - var branch = await File.ReadAllTextAsync(branchFilePath, Encoding.UTF8); - if (!string.Equals(branch.Trim(), "files-dev", StringComparison.OrdinalIgnoreCase)) - return; - } - catch { } - } - else - { - try - { - // Create branch file for users updating from versions earlier than v4.0.20. - await File.WriteAllTextAsync(branchFilePath, "files-dev", Encoding.UTF8); - } - catch { } - } - - var srcExeFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/FilesOpenDialog/Files.App.Launcher.exe")); - var destFolder = await StorageFolder.GetFolderFromPathAsync(destFolderPath); - - await srcExeFile.CopyAsync(destFolder, "Files.App.Launcher.exe", NameCollisionOption.ReplaceExisting); - - App.Logger.LogInformation("Files.App.Launcher updated."); - } - catch (Exception ex) - { - Logger?.LogError(ex, ex.Message); - return; - } - } - - public async Task CheckForReleaseNotesAsync() - { - using var client = new HttpClient(); - - try - { - var response = await client.GetAsync(Constants.ExternalUrl.ReleaseNotesUrl); - AreReleaseNotesAvailable = response.IsSuccessStatusCode; - } - catch - { - AreReleaseNotesAvailable = false; - } - } - - private async Task ApplyPackageUpdateAsync() - { - if (!IsUpdateAvailable) - return; - - IsUpdating = true; - - DeploymentResult? result = null; - - try - { - PackageManager packageManager = new PackageManager(); - - var restartStatus = PInvoke.RegisterApplicationRestart(null, (REGISTER_APPLICATION_RESTART_FLAGS)0); - App.AppModel.ForceProcessTermination = true; - - Logger?.LogInformation($"Register for restart: {restartStatus}"); - - await Task.Run(async () => - { - var appInstallerUri = new Uri(_sideloadVersion[PackageName]); - - var deployment = packageManager.AddPackageByAppInstallerFileAsync( - appInstallerUri, - AddPackageByAppInstallerOptions.ForceTargetAppShutdown, - packageManager.GetDefaultPackageVolume()); - - deployment.Progress = (op, progress) => - { - MainWindow.Instance.DispatcherQueue.TryEnqueue(() => - { - UpdateProgress = (int)progress.percentage; - }); - }; - - result = await deployment; - }); - } - catch (Exception e) - { - if (result?.ExtendedErrorCode is not null) - Logger?.LogInformation(result.ErrorText); - - Logger?.LogError(e, e.Message); - } - finally - { - // Reset fields - IsUpdating = false; - IsUpdateAvailable = false; - UpdateProgress = 0; - } - } - - public void Dispose() - { - _client?.Dispose(); - } - } -} diff --git a/src/Files.App/Services/PreviewPopupProviders/PreviewPopupService.cs b/src/Files.App/Services/PreviewPopupProviders/PreviewPopupService.cs index 7d13aa56974f..aaf1148271ba 100644 --- a/src/Files.App/Services/PreviewPopupProviders/PreviewPopupService.cs +++ b/src/Files.App/Services/PreviewPopupProviders/PreviewPopupService.cs @@ -10,10 +10,6 @@ internal sealed partial class PreviewPopupService : ObservableObject, IPreviewPo { if (await QuickLookProvider.Instance.DetectAvailability()) return await Task.FromResult(QuickLookProvider.Instance); -#if WINDOWS - if (await SeerProProvider.Instance.DetectAvailability()) - return await Task.FromResult(SeerProProvider.Instance); -#endif if (await PowerToysPeekProvider.Instance.DetectAvailability()) return await Task.FromResult(PowerToysPeekProvider.Instance); else diff --git a/src/Files.App/Services/PreviewPopupProviders/SeerProProvider.cs b/src/Files.App/Services/PreviewPopupProviders/SeerProProvider.cs deleted file mode 100644 index 0b98264b0b4a..000000000000 --- a/src/Files.App/Services/PreviewPopupProviders/SeerProProvider.cs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; -using System.IO; -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.DataExchange; - -namespace Files.App.Services.PreviewPopupProviders -{ - public sealed class SeerProProvider : IPreviewPopupProvider - { - public static SeerProProvider Instance { get; } = new(); - - private string? CurrentPath; - private HWND? _cachedSeerWindowHandle; - - private bool? _IsTrackSelectionSettingEnabledCache; - private bool IsTrackSelectionSettingEnabled - { - get - { - _IsTrackSelectionSettingEnabledCache ??= DetectTrackSelectionSetting().Result; - - return _IsTrackSelectionSettingEnabledCache.Value; - } - } - - private HWND GetSeerWindowHandle() - { - _cachedSeerWindowHandle ??= PInvoke.FindWindow("SeerWindowClass", null); - return _cachedSeerWindowHandle.Value; - } - - public unsafe Task TogglePreviewPopupAsync(string path) - { - COPYDATASTRUCT data = default; - data.dwData = 5000u; - data.cbData = (uint)(path.Length + 1) * 2; - data.lpData = (void*)Marshal.StringToHGlobalUni(path); - - var pData = Marshal.AllocHGlobal(Marshal.SizeOf(data)); - Marshal.StructureToPtr(data, pData, false); - - HWND hWnd = GetSeerWindowHandle(); - PInvoke.SendMessage(hWnd, 0x004A /*WM_COPYDATA*/, 0, pData); - - bool isVisible = PInvoke.IsWindowVisible(hWnd); - CurrentPath = isVisible ? path : null; - - Marshal.FreeHGlobal((nint)data.lpData); - Marshal.FreeHGlobal(pData); - return Task.CompletedTask; - } - - public async Task SwitchPreviewAsync(string path) - { - HWND hWnd = GetSeerWindowHandle(); - bool isWindowVisible = PInvoke.IsWindowVisible(hWnd); - - if (CurrentPath is not null && !isWindowVisible) - { - CurrentPath = null; - return; - } - - // Close preview window is track selection setting is disabled - if (!IsTrackSelectionSettingEnabled && !string.IsNullOrEmpty(CurrentPath)) - { - await TogglePreviewPopupAsync(CurrentPath); - return; - } - - // Update the preview window if the path changed and window is currently open - if (CurrentPath is not null && path != CurrentPath && isWindowVisible) - await TogglePreviewPopupAsync(path); - } - - public async unsafe Task DetectAvailability() - { - var hWnd = (nint)GetSeerWindowHandle().Value; - return hWnd != nint.Zero && hWnd.ToInt64() != -1; - } - - private Task DetectTrackSelectionSetting() - { - bool trackSelectedFile = true; - - var keyName = @"HKEY_CURRENT_USER\Software\Corey\Seer"; - var value = Registry.GetValue(keyName, "tracking_file", null); - - if (bool.TryParse(value?.ToString(), out var result)) - return Task.FromResult(result); - - // List of possible paths for the Seer Pro settings file - string[] paths = - { - Environment.ExpandEnvironmentVariables("%USERPROFILE%\\Documents\\Seer\\uwp.ini"), - Environment.ExpandEnvironmentVariables("%USERPROFILE%\\appdata\\Local\\Packages\\CNABA5E861-AC2A-4523-B3C1.Seer-AWindowsQuickLookTo_p7t0z30wh4868\\LocalCache\\Local\\Corey\\Seer\\uwp.ini"), - Environment.ExpandEnvironmentVariables("%USERPROFILE%\\appdata\\Local\\Corey\\Seer\\uwp.ini"), - Environment.ExpandEnvironmentVariables("%USERPROFILE%\\Documents\\Seer\\config.ini") - }; - - // Find the first existing path - foreach (var path in paths) - { - if (File.Exists(path)) - { - // Read the settings file and look for the tracking_file setting - string[] lines = File.ReadAllLines(path); - - foreach (var line in lines) - { - if (line.StartsWith("tracking_file", StringComparison.OrdinalIgnoreCase)) - { - string[] keyValue = line.Split('='); - if (keyValue.Length == 2 && bool.TryParse(keyValue[1].Trim(), out bool isTrackingFile)) - { - trackSelectedFile = isTrackingFile; - break; - } - } - } - - break; - } - } - - return Task.FromResult(trackSelectedFile); - } - } -} diff --git a/src/Files.App/Services/Settings/FileTagsSettingsService.cs b/src/Files.App/Services/Settings/FileTagsSettingsService.cs index b4375da3d02c..76f1da30cb23 100644 --- a/src/Files.App/Services/Settings/FileTagsSettingsService.cs +++ b/src/Files.App/Services/Settings/FileTagsSettingsService.cs @@ -38,12 +38,7 @@ public FileTagsSettingsService() var settingsSerializer = new DefaultSettingsSerializer(message => App.Logger.LogWarning(message)); SettingsSerializer = settingsSerializer; - #if WINDOWS - Initialize(Path.Combine(ApplicationData.Current.LocalFolder.Path, - Constants.LocalSettings.SettingsFolderName, Constants.LocalSettings.FileTagSettingsFileName)); -#else Initialize(Ioc.Default.GetRequiredService().FileTagsSettingsFilePath); -#endif var jsonSettingsSerializer = new DefaultJsonSettingsSerializer(); JsonSettingsSerializer = jsonSettingsSerializer; @@ -187,21 +182,7 @@ private int GetTagIndex(string uid) private void UntagAllFiles(string uid) { -#if !WINDOWS _ = FileTagsHelper.UntagAllFilesAsync(uid); -#else - var tagDoDelete = new string[] { uid }; - - foreach (var item in FileTagsHelper.GetDbInstance().GetAll()) - { - if (item.Tags.Contains(uid)) - { - _ = FileTagsHelper.WriteFileTagAsync( - item.FilePath, - item.Tags.Except(tagDoDelete).ToArray()); - } - } -#endif } private IJsonSettingsSerializer GetJsonSettingsSerializer() diff --git a/src/Files.App/Services/Settings/UserSettingsService.cs b/src/Files.App/Services/Settings/UserSettingsService.cs index 5a68db73142f..ee01ea167e23 100644 --- a/src/Files.App/Services/Settings/UserSettingsService.cs +++ b/src/Files.App/Services/Settings/UserSettingsService.cs @@ -94,12 +94,8 @@ public UserSettingsService() var settingsSerializer = new DefaultSettingsSerializer(message => App.Logger.LogWarning(message)); SettingsSerializer = settingsSerializer; - #if WINDOWS - Initialize(Path.Combine(ApplicationData.Current.LocalFolder.Path, Constants.LocalSettings.SettingsFolderName, Constants.LocalSettings.UserSettingsFileName)); -#else // XDG location (~/.config/Files/settings/user_settings.json) Initialize(Ioc.Default.GetRequiredService().UserSettingsFilePath); -#endif var jsonSettingsSerializer = new DefaultJsonSettingsSerializer(); JsonSettingsSerializer = jsonSettingsSerializer; diff --git a/src/Files.App/Services/SizeProvider/CachedSizeProvider.Windows.cs b/src/Files.App/Services/SizeProvider/CachedSizeProvider.Windows.cs deleted file mode 100644 index 484ebc94cf76..000000000000 --- a/src/Files.App/Services/SizeProvider/CachedSizeProvider.Windows.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; - -namespace Files.App.Services.SizeProvider -{ - public sealed partial class CachedSizeProvider - { - public async Task UpdateAsync(string path, CancellationToken cancellationToken) - { - await Task.Yield(); - if (!sizes.ContainsKey(path)) - RaiseSizeChanged(path, 0, SizeChangedValueState.None); - - var stopwatch = Stopwatch.StartNew(); - ulong size = await Calculate(path); - - sizes[path] = size; - RaiseSizeChanged(path, size, SizeChangedValueState.Final); - - async Task Calculate(string path, int level = 0) - { - if (string.IsNullOrEmpty(path)) - return 0; - - static unsafe (FindCloseSafeHandle, WIN32_FIND_DATAW) FindFirstFileEx(string path) - { - WIN32_FIND_DATAW initialFindData = default; - var hFile = PInvoke.FindFirstFileEx($"{path}{Path.DirectorySeparatorChar}*.*", FINDEX_INFO_LEVELS.FindExInfoBasic, - &initialFindData, FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - var findData = initialFindData; - return (hFile, findData); - } - (FindCloseSafeHandle hFile, WIN32_FIND_DATAW findData) = FindFirstFileEx(path); - using FindCloseSafeHandle findHandleScope = hFile; - - ulong size = 0; - ulong localSize = 0; - string localPath = string.Empty; - - if (!hFile.IsInvalid) - { - do - { - if (((FileAttributes)findData.dwFileAttributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) - // Skip symbolic links and junctions - continue; - - bool isDirectory = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) is FileAttributes.Directory; - if (!isDirectory) - { - size += (ulong)findData.GetSize(); - } - else - { - string fileName = findData.cFileName.ToString(); - if (fileName is not "." and not "..") - { - localPath = Path.Combine(path, fileName); - localSize = await Calculate(localPath, level + 1); - size += localSize; - } - } - - if (level <= 3) - { - await Task.Yield(); - sizes[localPath] = localSize; - } - if (level is 0 && stopwatch.ElapsedMilliseconds > 500) - { - // Limit updates to every 0.5 seconds to prevent crashes due to frequent updates - stopwatch.Restart(); - RaiseSizeChanged(path, size, SizeChangedValueState.Intermediate); - } - - if (cancellationToken.IsCancellationRequested) - break; - } while (PInvoke.FindNextFile(hFile, out findData)); - } - return size; - } - } - } -} diff --git a/src/Files.App/Services/Storage/StorageArchiveService.cs b/src/Files.App/Services/Storage/StorageArchiveService.cs deleted file mode 100644 index d78b3f443f42..000000000000 --- a/src/Files.App/Services/Storage/StorageArchiveService.cs +++ /dev/null @@ -1,531 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Files.Shared.Helpers; -using ICSharpCode.SharpZipLib.Core; -using ICSharpCode.SharpZipLib.Zip; -using Microsoft.Extensions.Logging; -using SevenZip; -using System.Collections.Concurrent; -using System.IO; -using System.Text; -using UtfUnknown; -using Windows.Storage; -using Windows.Win32; - -namespace Files.App.Services -{ - /// - public class StorageArchiveService : IStorageArchiveService - { - private StatusCenterViewModel StatusCenterViewModel { get; } = Ioc.Default.GetRequiredService(); - - // Archive paths currently being written. ConcurrentDictionary used as a set; the byte value - // is unused. Lookups are case-insensitive to match Windows path semantics. - private readonly ConcurrentDictionary inProgressArchives = - new(StringComparer.OrdinalIgnoreCase); - - /// - public event EventHandler? CompressionCompleted; - - /// - public bool IsCompressionInProgress(string archivePath) - => inProgressArchives.ContainsKey(archivePath); - - /// - public bool CanCompress(IReadOnlyList items) - { - return - CanDecompress(items) is false || - items.Count > 1; - } - - /// - public bool CanDecompress(IReadOnlyList items) - { - return - items.Any() && - (items.All(x => x.IsArchive) || - items.All(x => - x.PrimaryItemAttribute == StorageItemTypes.File && - FileExtensionHelpers.IsZipFile(x.FileExtension))); - } - - /// - public async Task CompressAsync(ICompressArchiveModel compressionModel) - { - var archivePath = compressionModel.GetArchivePath(); - - int index = 1; - - while (SystemIO.File.Exists(archivePath) || SystemIO.Directory.Exists(archivePath)) - archivePath = compressionModel.GetArchivePath($" ({++index})"); - - compressionModel.ArchivePath = archivePath; - - var banner = StatusCenterHelper.AddCard_Compress( - compressionModel.Sources, - archivePath.CreateEnumerable(), - ReturnResult.InProgress, - compressionModel.Sources.Count()); - - compressionModel.Progress = banner.ProgressEventSource; - compressionModel.CancellationToken = banner.CancellationToken; - - inProgressArchives.TryAdd(archivePath, 0); - - bool isSuccess; - try - { - isSuccess = await compressionModel.RunCreationAsync(); - } - finally - { - inProgressArchives.TryRemove(archivePath, out _); - } - - StatusCenterViewModel.RemoveItem(banner); - - if (isSuccess) - { - StatusCenterHelper.AddCard_Compress( - compressionModel.Sources, - archivePath.CreateEnumerable(), - ReturnResult.Success, - compressionModel.Sources.Count()); - - CompressionCompleted?.Invoke(this, archivePath); - } - else - { - PInvoke.DeleteFileFromApp(archivePath); - - StatusCenterHelper.AddCard_Compress( - compressionModel.Sources, - archivePath.CreateEnumerable(), - compressionModel.CancellationToken.IsCancellationRequested || compressionModel.IsCancelled - ? ReturnResult.Cancelled - : ReturnResult.Failed, - compressionModel.Sources.Count()); - } - - return isSuccess; - } - - /// - public Task DecompressAsync(string archiveFilePath, string destinationFolderPath, string password = "", Encoding? encoding = null) - { - if (encoding == null) - { - return DecompressAsyncWithSevenZip(archiveFilePath, destinationFolderPath, password); - } - else - { - return DecompressAsyncWithSharpZipLib(archiveFilePath, destinationFolderPath, password, encoding); - } - } - async Task DecompressAsyncWithSevenZip(string archiveFilePath, string destinationFolderPath, string password = "") - { - if (string.IsNullOrEmpty(archiveFilePath) || - string.IsNullOrEmpty(destinationFolderPath)) - return false; - - using var zipFile = await GetSevenZipExtractorAsync(archiveFilePath, password); - if (zipFile is null) - return false; - - // Initialize a new in-progress status card - var statusCard = StatusCenterHelper.AddCard_Decompress( - archiveFilePath.CreateEnumerable(), - destinationFolderPath.CreateEnumerable(), - ReturnResult.InProgress); - - // Check if the decompress operation canceled - if (statusCard.CancellationToken.IsCancellationRequested) - return false; - - StatusCenterItemProgressModel fsProgress = new( - statusCard.ProgressEventSource, - enumerationCompleted: true, - FileSystemStatusCode.InProgress, - zipFile.ArchiveFileData.Count(x => !x.IsDirectory)); - - fsProgress.TotalSize = zipFile.ArchiveFileData.Select(x => (long)x.Size).Sum(); - fsProgress.Report(); - - zipFile.Extracting += (s, e) => - { - if (fsProgress.TotalSize > 0) - fsProgress.Report(e.BytesProcessed / (double)fsProgress.TotalSize * 100); - }; - - zipFile.FileExtractionStarted += (s, e) => - { - if (statusCard.CancellationToken.IsCancellationRequested) - e.Cancel = true; - - if (!e.FileInfo.IsDirectory) - { - fsProgress.FileName = ArchiveEntryHelpers.GetEntryName(e.FileInfo, archiveFilePath); - fsProgress.Report(); - } - }; - - zipFile.FileExtractionFinished += (s, e) => - { - if (!e.FileInfo.IsDirectory) - { - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - } - }; - - bool isSuccess = false; - - try - { - var files = zipFile.ArchiveFileData.Where(x => !x.IsDirectory).ToList(); - var resolvedName = files.Count is 1 ? ArchiveEntryHelpers.GetEntryName(files[0], archiveFilePath) : null; - - if (resolvedName is not null && resolvedName != files[0].FileName) - { - // ExtractArchive would write the entry's "[no name]" placeholder to disk - var destinationPath = ValidateAndGetSafeExtractionPath(destinationFolderPath, resolvedName); - Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); - await using var destinationStream = File.Create(destinationPath); - await zipFile.ExtractFileAsync(files[0].Index, destinationStream); - } - else - { - foreach (var archiveEntry in zipFile.ArchiveFileData) - _ = ValidateAndGetSafeExtractionPath(destinationFolderPath, archiveEntry.FileName, archiveEntry.IsDirectory); - - // TODO: Get this method return result - await zipFile.ExtractArchiveAsync(destinationFolderPath); - } - - if (!statusCard.CancellationToken.IsCancellationRequested) - isSuccess = true; - } - catch (Exception ex) - { - isSuccess = false; - App.Logger.LogError(ex, "SevenZipLib error extracting archive file."); - } - finally - { - // Remove the in-progress status card - StatusCenterViewModel.RemoveItem(statusCard); - - if (isSuccess) - { - // Successful - StatusCenterHelper.AddCard_Decompress( - archiveFilePath.CreateEnumerable(), - destinationFolderPath.CreateEnumerable(), - ReturnResult.Success); - } - else - { - // Error - StatusCenterHelper.AddCard_Decompress( - archiveFilePath.CreateEnumerable(), - destinationFolderPath.CreateEnumerable(), - statusCard.CancellationToken.IsCancellationRequested - ? ReturnResult.Cancelled - : ReturnResult.Failed); - } - } - - return isSuccess; - } - - async Task DecompressAsyncWithSharpZipLib(string archiveFilePath, string destinationFolderPath, string password, Encoding encoding) - { - if (string.IsNullOrEmpty(archiveFilePath) || - string.IsNullOrEmpty(destinationFolderPath)) - return false; - using var zipFile = new ZipFile(archiveFilePath, StringCodec.FromEncoding(encoding)); - if (zipFile is null) - return false; - - if (!string.IsNullOrEmpty(password)) - zipFile.Password = password; - - // Initialize a new in-progress status card - var statusCard = StatusCenterHelper.AddCard_Decompress( - archiveFilePath.CreateEnumerable(), - destinationFolderPath.CreateEnumerable(), - ReturnResult.InProgress); - - // Check if the decompress operation canceled - if (statusCard.CancellationToken.IsCancellationRequested) - return false; - - StatusCenterItemProgressModel fsProgress = new( - statusCard.ProgressEventSource, - enumerationCompleted: true, - FileSystemStatusCode.InProgress, - zipFile.Cast().Count(x => !x.IsDirectory)); - fsProgress.TotalSize = zipFile.Cast().Select(x => (long)x.Size).Sum(); - fsProgress.Report(); - - bool isSuccess = false; - - try - { - long processedBytes = 0; - int processedFiles = 0; - await Task.Run(() => - { - foreach (ZipEntry zipEntry in zipFile) - { - if (statusCard.CancellationToken.IsCancellationRequested) - { - isSuccess = false; - break; - } - - if (!zipEntry.IsFile) - { - continue; // Ignore directories - } - - string entryFileName = zipEntry.Name; - string fullZipToPath = ValidateAndGetSafeExtractionPath(destinationFolderPath, entryFileName); - string? directoryName = Path.GetDirectoryName(fullZipToPath); - - if (directoryName is not null && !Directory.Exists(directoryName)) - { - Directory.CreateDirectory(directoryName); - } - - byte[] buffer = new byte[4096]; // 4K is a good default - using (Stream zipStream = zipFile.GetInputStream(zipEntry)) - using (FileStream streamWriter = File.Create(fullZipToPath)) - { - fsProgress.FileName = entryFileName; - fsProgress.Report(); - - StreamUtils.Copy(zipStream, streamWriter, buffer); - } - processedBytes += zipEntry.Size; - if (fsProgress.TotalSize > 0) - { - fsProgress.Report(processedBytes / (double)fsProgress.TotalSize * 100); - } - processedFiles++; - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - } - }); - if (!statusCard.CancellationToken.IsCancellationRequested) - { - isSuccess = true; - } - } - catch (Exception ex) - { - isSuccess = false; - App.Logger.LogError(ex, "SharpZipLib error during decompression."); - } - finally - { - // Remove the in-progress status card - StatusCenterViewModel.RemoveItem(statusCard); - - if (isSuccess) - { - // Successful - StatusCenterHelper.AddCard_Decompress( - archiveFilePath.CreateEnumerable(), - destinationFolderPath.CreateEnumerable(), - ReturnResult.Success); - } - else - { - // Error - StatusCenterHelper.AddCard_Decompress( - archiveFilePath.CreateEnumerable(), - destinationFolderPath.CreateEnumerable(), - statusCard.CancellationToken.IsCancellationRequested - ? ReturnResult.Cancelled - : ReturnResult.Failed); - } - - if (zipFile != null) - { - zipFile.IsStreamOwner = true; // Makes close also close the underlying stream - zipFile.Close(); - } - } - return isSuccess; - } - - private static string ValidateAndGetSafeExtractionPath(string destinationFolderPath, string entryName, bool allowDestinationRoot = false) - { - var destinationRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(destinationFolderPath)); - var destinationPrefix = Path.EndsInDirectorySeparator(destinationRoot) - ? destinationRoot - : destinationRoot + Path.DirectorySeparatorChar; - var normalizedEntryName = entryName.Replace('/', Path.DirectorySeparatorChar); - var destinationPath = Path.GetFullPath(Path.Combine(destinationPrefix, normalizedEntryName)); - - if (string.Equals(destinationPath, destinationRoot, StringComparison.Ordinal)) - { - return allowDestinationRoot - ? destinationPath - : throw new InvalidDataException($"Archive entry '{entryName}' resolves to the destination folder instead of a file path."); - } - - if (!destinationPath.StartsWith(destinationPrefix, StringComparison.Ordinal)) - throw new InvalidDataException($"Archive entry '{entryName}' resolves outside the destination folder."); - - var currentPath = destinationRoot; - var relativePath = Path.GetRelativePath(destinationRoot, destinationPath); - foreach (var pathSegment in relativePath.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) - { - currentPath = Path.Combine(currentPath, pathSegment); - try - { - if (File.GetAttributes(currentPath).HasFlag(System.IO.FileAttributes.ReparsePoint)) - throw new InvalidDataException($"Archive entry '{entryName}' traverses a reparse point."); - } - catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) - { - break; - } - } - - return destinationPath; - } - - - /// - public string GenerateArchiveNameFromItems(IReadOnlyList items) - { - if (!items.Any()) - return string.Empty; - - return - SystemIO.Path.GetFileName( - items.Count is 1 - ? items[0].ItemPath - : SystemIO.Path.GetDirectoryName(items[0].ItemPath)) - ?? string.Empty; - } - - /// - public async Task HasMultipleTopLevelEntriesAsync(string archiveFilePath, string password = "") - { - var result = await FilesystemTasks.Wrap(async () => - { - using SevenZipExtractor? zipFile = await GetSevenZipExtractorAsync(archiveFilePath, password); - if (zipFile is null) - return true; - - string? firstTopLevel = null; - foreach (var file in zipFile.ArchiveFileData) - { - var segment = file.FileName.Split(['/', '\\'], StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(x => x is not "." and not ".."); - if (segment is null) - continue; - - if (firstTopLevel is null) - firstTopLevel = segment; - else if (segment != firstTopLevel) - return true; - } - - return false; - }); - - return result; - } - - /// - public async Task IsEncryptedAsync(string archiveFilePath) - { - using SevenZipExtractor? zipFile = await GetSevenZipExtractorAsync(archiveFilePath); - if (zipFile is null) - return true; - - return zipFile.ArchiveFileData.Any(file => file.Encrypted || file.Method.Contains("Crypto") || file.Method.Contains("AES")); - } - - /// - public async Task IsEncodingUndeterminedAsync(string archiveFilePath) - { - if (archiveFilePath is null) return false; - if (Path.GetExtension(archiveFilePath) != ".zip") return false; - try - { - using (ZipFile zipFile = new ZipFile(archiveFilePath)) - { - return !zipFile.Cast().All( - entry => entry.IsUnicodeText || entry.Name.All(c => char.IsAscii(c)) - ); - } - } - catch (Exception ex) - { - App.Logger.LogError(ex, "SharpZipLib error."); - return true; - } - } - - public async Task DetectEncodingAsync(string archiveFilePath) - { - //Temporarily using cp437 to decode zip file - //because SharpZipLib requires an encoding when decoding - //and cp437 contains all bytes as character - //which means that we can store any byte array as cp437 string losslessly - var cp437 = Encoding.GetEncoding(437); - try - { - using (ZipFile zipFile = new ZipFile(archiveFilePath, StringCodec.FromEncoding(cp437))) - { - var fileNameBytes = cp437.GetBytes( - String.Join("\n", - zipFile.Cast() - .Where(e => !e.IsUnicodeText) - .Select(e => e.Name) - ) - ); - var detectionResult = CharsetDetector.DetectFromBytes(fileNameBytes); - if (detectionResult.Detected != null && detectionResult.Detected.Confidence > 0.5) - { - return detectionResult.Detected.Encoding; - } - else - { - return null; - } - } - } - catch (Exception ex) - { - App.Logger.LogError(ex, "SharpZipLib error detecting encoding."); - return null; - } - } - - /// - public async Task GetSevenZipExtractorAsync(string archiveFilePath, string password = "") - { - return await FilesystemTasks.WrapNullable(async () => - { - BaseStorageFile? archive = await StorageHelpers.ToStorageItem(archiveFilePath); - if (archive is null) - return null; - - var extractor = string.IsNullOrEmpty(password) - ? new SevenZipExtractor(archive.Path) - : new SevenZipExtractor(archive.Path, password); - - // Force to load archive (1665013614u) - return extractor.ArchiveFileData is null ? null : extractor; - }); - } - } -} diff --git a/src/Files.App/Services/Storage/StorageDevicesService.cs b/src/Files.App/Services/Storage/StorageDevicesService.cs index 6124173bbb9f..1d4e93f27195 100644 --- a/src/Files.App/Services/Storage/StorageDevicesService.cs +++ b/src/Files.App/Services/Storage/StorageDevicesService.cs @@ -12,16 +12,11 @@ public sealed class RemovableDrivesService : IRemovableDrivesService { public IStorageDeviceWatcher CreateWatcher() { -#if WINDOWS - return new WindowsStorageDeviceWatcher(); -#else return new LinuxStorageDeviceWatcher(); -#endif } public async IAsyncEnumerable GetDrivesAsync() { -#if !WINDOWS // Mounted drives (mountinfo + UDisks2 labels), volumes that are not mounted yet and MTP devices (GVfs) var entries = await LinuxDriveCatalog.EnumerateAsync().ConfigureAwait(false); var linuxPending = entries.Select(entry => entry.CreateAsync()).ToList(); @@ -31,19 +26,6 @@ public async IAsyncEnumerable GetDrivesAsync() if (await completed is { } linuxItem) yield return linuxItem; } -#else - var pCloudDrivePath = App.AppModel.PCloudDrivePath; - var drives = await Task.Run(DriveInfo.GetDrives).ConfigureAwait(false); - - // Probe drives in parallel so one slow drive doesn't delay the rest - var pending = drives.Select(drive => GetDriveItemAsync(drive, pCloudDrivePath)).ToList(); - - await foreach (var completed in Task.WhenEach(pending)) - { - if (await completed is { } driveItem) - yield return driveItem; - } -#endif } private static async Task GetDriveItemAsync(DriveInfo drive, string pCloudDrivePath) @@ -91,12 +73,8 @@ public async IAsyncEnumerable GetDrivesAsync() public Task GetPrimaryDriveAsync() { -#if WINDOWS - var cDrivePath = $@"{Constants.UserEnvironmentPaths.SystemDrivePath}\"; -#else // LINUX-TODO(drives): primary drive is the root file system var cDrivePath = "/"; -#endif if (!Directory.Exists(cDrivePath)) { App.Logger.LogWarning($"Primary system drive '{cDrivePath}' could not be found."); diff --git a/src/Files.App/Services/Storage/StorageNetworkService.cs b/src/Files.App/Services/Storage/StorageNetworkService.cs index 2164ed8c1532..21edc24e61f4 100644 --- a/src/Files.App/Services/Storage/StorageNetworkService.cs +++ b/src/Files.App/Services/Storage/StorageNetworkService.cs @@ -1,31 +1,11 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if WINDOWS -using System.Text; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.NetworkManagement.WNet; -using Windows.Win32.Security.Credentials; -#endif namespace Files.App.Services { public sealed partial class NetworkService : ObservableObject, INetworkService { -#if WINDOWS - private ICommonDialogService CommonDialogService { get; } = Ioc.Default.GetRequiredService(); - - private readonly static string guid = "::{f02c1a0d-be21-4350-88b0-7367fc96ef3c}"; - - // Virtual disk path prefixes that don't work with Windows networking APIs - private readonly static string[] VirtualDiskPrefixes = - [ - @"\\RaiDrive-", - @"\\cryptomator-vault\", - @"\\EgnyteDrive\" - ]; -#endif private ObservableCollection _Computers = []; @@ -53,11 +33,7 @@ public NetworkService() { DeviceID = "network-folder", Text = Strings.Network.GetLocalizedResource(), -#if WINDOWS - Path = Constants.UserEnvironmentPaths.NetworkFolderPath, -#else Path = NetworkRootPath, -#endif Type = DriveType.Network, ItemType = NavigationControlItemType.Drive, }; @@ -72,97 +48,20 @@ public NetworkService() lock (_Computers) _Computers.Add(networkItem); -#if !WINDOWS StartLinuxWatching(); -#endif } /// public async Task> GetComputersAsync() { -#if !WINDOWS // Connected GVfs locations (smb, sftp, ftp, dav, nfs...); LINUX-TODO(network-discovery): browse the LAN with Avahi return await Task.FromResult(GetLinuxNetworkItems()); -#else - var result = await Win32Helper.GetShellFolderAsync(guid, false, true, 0, int.MaxValue); - - return result.Enumerate.Where(item => item.IsFolder).Select(item => - { - var networkItem = new DriveItem() - { - Text = item.FileName, - Path = item.FilePath, - DeviceID = item.FilePath, - Type = DriveType.Network, - ItemType = NavigationControlItemType.Drive, - }; - - networkItem.MenuOptions = new ContextMenuOptions() - { - IsLocationItem = true, - ShowEjectDevice = networkItem.IsRemovable, - ShowShellItems = true, - ShowProperties = true, - }; - - return networkItem; - }); -#endif } /// public async Task> GetShortcutsAsync() { -#if !WINDOWS return await Task.FromResult(GetLinuxNetworkItems()); -#else - var networkLocations = await STATask.Run(() => - { - var locations = new List(); - using (var netHood = new ShellFolder(PInvoke.FOLDERID_NetHood)) - { - foreach (var item in netHood) - { - if (item is ShellLink link) - { - if (ShellFolderExtensions.GetShellLinkItem(link) is { } linkItem) - locations.Add(linkItem); - } - else - { - var linkPath = item.Properties["System.Link.TargetParsingPath"] as string; - if (linkPath is not null && - ShellFolderExtensions.GetShellFileItem(item) is { } linkItem) - { - locations.Add(new(linkItem) { TargetPath = linkPath }); - } - } - } - } - return locations; - }, App.Logger); - - return (networkLocations ?? Enumerable.Empty()).Select(item => - { - var networkItem = new DriveItem() - { - Text = item.FileName, - Path = item.TargetPath, - DeviceID = item.FilePath, - Type = DriveType.Network, - ItemType = NavigationControlItemType.Drive, - }; - - networkItem.MenuOptions = new ContextMenuOptions() - { - IsLocationItem = true, - ShowEjectDevice = networkItem.IsRemovable, - ShowShellItems = true, - ShowProperties = true, - }; - return networkItem; - }); -#endif } /// @@ -205,166 +104,5 @@ public async Task UpdateShortcutsAsync() Shortcuts.AddIfNotPresent(item); } -#if WINDOWS - /// - public Task GetNetworkAvailabilityAsync() - { - return STATask.Run(() => DetectionAndSharingHelper.GetNetworkAvailability(), App.Logger); - } - - /// - public Task OpenNetworkSharingSettingsAsync() - { - return STATask.Run(DetectionAndSharingHelper.OpenNetworkSharingSettings, App.Logger); - } - - /// - public bool DisconnectNetworkDrive(IFolder drive) - { - return - PInvoke.WNetCancelConnection2W( - drive.Id.TrimEnd('\\'), - NET_CONNECT_FLAGS.CONNECT_UPDATE_PROFILE, - true) - is WIN32_ERROR.NO_ERROR; - } - - /// - public Task OpenMapNetworkDriveDialogAsync() - { - return STATask.Run(() => - { - return CommonDialogService.Open_NetworkConnectionDialog( - MainWindow.Instance.WindowHandle, - useMostRecentPath: true, - hideRestoreConnectionCheckBox: false); - }, App.Logger); - } - - /// - public async Task AuthenticateNetworkShare(string path, CancellationToken cancellationToken) - { - if (await Task.Run(() => - { - unsafe - { - if (!path.StartsWith(@"\\", StringComparison.Ordinal)) - { - // Special handling for network drives - // This part will change path from "y:\Download" to "\\192.168.0.1\nfs\Download" - Span remoteName = stackalloc char[300]; - uint length = (uint)remoteName.Length; - string lpLocalName = path.Substring(0, 2); - - WIN32_ERROR ret = PInvoke.WNetGetConnection(lpLocalName, remoteName, ref length); - - if (ret == WIN32_ERROR.NO_ERROR) - path = path.Replace(lpLocalName, remoteName[..(int)length].TrimEnd('\0').ToString()); - - } - - // Skip authentication for virtual disk shares - // These providers create virtual disk paths that don't work with Windows networking APIs - if (VirtualDiskPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) - { - return (Skip: true, Result: WIN32_ERROR.NO_ERROR); - } - - // WNetAddConnection3W only accepts "\\server" or "\\server\share" as lpRemoteName; - // deeper paths fail (e.g. ERROR_DIRECTORY when the path points to a file such as an archive) - var shareRootSegments = path.Substring(2).Split('\\', StringSplitOptions.RemoveEmptyEntries); - if (shareRootSegments.Length > 2) - path = @"\\" + shareRootSegments[0] + @"\" + shareRootSegments[1]; - - // If credentials are saved, this will return NO_ERROR - fixed (char* lpcPath = path) - { - var netRes = new NETRESOURCEW() - { - dwType = NET_RESOURCE_TYPE.RESOURCETYPE_DISK, - lpRemoteName = new PWSTR(lpcPath) - }; - - return (Skip: false, Result: (WIN32_ERROR)PInvoke.WNetAddConnection3W(new(nint.Zero), netRes, null, null, 0)); - } - } - }) is not (Skip: false, Result: var res)) - { - return true; - } - - if (cancellationToken.IsCancellationRequested) return false; - - if (res == WIN32_ERROR.ERROR_LOGON_FAILURE || res == WIN32_ERROR.ERROR_ACCESS_DENIED) - { - var dialog = DynamicDialogFactory.GetFor_CredentialEntryDialog(path); - await dialog.ShowAsync(); - var credentialsReturned = dialog.ViewModel.AdditionalData as string[]; - - if (credentialsReturned is not null && credentialsReturned[1] != null) - { - res = await Task.Run(() => - { - unsafe - { - fixed (char* lpcPath = path) - { - var netRes = new NETRESOURCEW() - { - dwType = NET_RESOURCE_TYPE.RESOURCETYPE_DISK, - lpRemoteName = new PWSTR(lpcPath) - }; - - return (WIN32_ERROR)PInvoke.WNetAddConnection3W(new(nint.Zero), netRes, credentialsReturned[1], credentialsReturned[0], 0); - } - } - }); - - if (credentialsReturned[2] == "y" && res == WIN32_ERROR.NO_ERROR) - { - var creds = new CREDENTIALW() - { - Type = CRED_TYPE.CRED_TYPE_DOMAIN_PASSWORD, - AttributeCount = 0, - Persist = CRED_PERSIST.CRED_PERSIST_ENTERPRISE - }; - - unsafe - { - fixed (char* lpcTargetName = path.Substring(2)) - creds.TargetName = new(lpcTargetName); - - fixed (char* lpcUserName = credentialsReturned[0]) - creds.UserName = new(lpcUserName); - - byte[] bPassword = Encoding.Unicode.GetBytes(credentialsReturned[1]); - fixed (byte* lpCredentialBlob = bPassword) - creds.CredentialBlob = lpCredentialBlob; - - creds.CredentialBlobSize = (uint)bPassword.Length; - } - - PInvoke.CredWrite(creds, 0); - } - } - else - { - return false; - } - } - - if (res == WIN32_ERROR.ERROR_LOGON_FAILURE || res == WIN32_ERROR.ERROR_ACCESS_DENIED) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.NetworkFolderErrorDialogTitle.GetLocalizedResource(), res.ToString()); - - return false; - } - - // Other results (e.g. ERROR_SESSION_CREDENTIAL_CONFLICT when a connection already exists, - // or provider errors on unusual paths) don't imply the share is inaccessible through the - // SMB redirector — proceed and let the enumeration itself surface any failure. - return true; - } -#endif } } diff --git a/src/Files.App/Services/Storage/StorageSecurityService.Windows.cs b/src/Files.App/Services/Storage/StorageSecurityService.Windows.cs deleted file mode 100644 index c20ea391c91e..000000000000 --- a/src/Files.App/Services/Storage/StorageSecurityService.Windows.cs +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using System.Security.Principal; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Security; -using Windows.Win32.Security.Authorization; -using Windows.Win32.System.Memory; -using SystemSecurity = System.Security.AccessControl; - -namespace Files.App.Services -{ - /// - public class StorageSecurityService : IStorageSecurityService - { - /// - public unsafe string GetOwner(string path) - { - var result = PInvoke.GetNamedSecurityInfo( - path, - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, - out var pSidOwner, - out _, - out _, - out _, - out var pSecurityDescriptor); - if (result is not WIN32_ERROR.ERROR_SUCCESS) - return string.Empty; - - try - { - if (!PInvoke.ConvertSidToStringSid(pSidOwner, out var sid)) - return string.Empty; - - try - { - return sid.ToString(); - } - finally - { - Marshal.FreeHGlobal((nint)sid.Value); - } - } - finally - { - Marshal.FreeHGlobal((nint)pSecurityDescriptor.Value); - } - } - - /// - public unsafe bool SetOwner(string path, string sid) - { - PSID pSid = default; - - // Get SID - fixed (char* cSid = sid) - { - if (!PInvoke.ConvertStringSidToSid(new PCWSTR(cSid), &pSid)) - return false; - } - - try - { - WIN32_ERROR result; - fixed (char* cPath = path) - { - // Change owner - result = PInvoke.SetNamedSecurityInfo( - new PWSTR(cPath), - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION, - pSid, - new PSID((void*)0)); - } - - // Run PowerShell as Admin - if (result is not WIN32_ERROR.ERROR_SUCCESS) - { - return Win32Helper.RunPowershellCommand( - $"-command \"try {{ $path = {Win32Helper.ToPowerShellStringLiteral(path)}; $ID = new-object System.Security.Principal.SecurityIdentifier({Win32Helper.ToPowerShellStringLiteral(sid)}); $acl = get-acl -LiteralPath $path; $acl.SetOwner($ID); set-acl -LiteralPath $path -aclObject $acl }} catch {{ exit 1; }}\"", - PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - } - - return true; - } - finally - { - Marshal.FreeHGlobal((nint)pSid.Value); - } - } - - /// - public FileSecurityResult GetAcl(string path, bool isFolder, out AccessControlList acl) - => GetAclCore(path, isFolder, out acl).ToFileSecurityResult(); - - private unsafe WIN32_ERROR GetAclCore(string path, bool isFolder, out AccessControlList acl) - { - acl = new(); - - // Get DACL - var result = PInvoke.GetNamedSecurityInfo( - path, - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION, - out _, - out _, - out ACL* pDACL, - out _, - out var pSecurityDescriptor); - - if (result is not WIN32_ERROR.ERROR_SUCCESS) - return result; - - try - { - if (pDACL == null) - return WIN32_ERROR.ERROR_SUCCESS; - - ACL_SIZE_INFORMATION aclSizeInfo = default; - - // Get ACL size info - bool bResult = PInvoke.GetAclInformation( - pDACL, - &aclSizeInfo, - (uint)Marshal.SizeOf(), - ACL_INFORMATION_CLASS.AclSizeInformation); - - if (!bResult) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - // Get owner - var szOwnerSid = GetOwner(path); - var principal = new AccessControlPrincipal(szOwnerSid); - - var isValidAcl = PInvoke.IsValidAcl(pDACL); - List aces = []; - - // Get ACEs - for (uint i = 0; i < aclSizeInfo.AceCount; i++) - { - bResult = PInvoke.GetAce(*pDACL, i, out var pAce); - if (!bResult) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - if (pAce is null) - continue; - - var ace = Marshal.PtrToStructure((nint)pAce); - var offset = Marshal.SizeOf() + sizeof(uint); - nint pAcePtr = new((long)pAce + offset); - if (!PInvoke.ConvertSidToStringSid((PSID)pAcePtr, out var pszSid)) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - try - { - AccessControlEntryType type; - AccessControlEntryFlags inheritanceFlags = AccessControlEntryFlags.None; - AccessMaskFlags accessMaskFlags = (AccessMaskFlags)ace.Mask; - - var header = ace.Header; - type = (SystemSecurity.AceType)header.AceType switch - { - SystemSecurity.AceType.AccessAllowed => AccessControlEntryType.Allow, - _ => AccessControlEntryType.Deny - }; - - var flags = (SystemSecurity.AceFlags)header.AceFlags; - bool isInherited = flags.HasFlag(SystemSecurity.AceFlags.Inherited); - - if (flags.HasFlag(SystemSecurity.AceFlags.ContainerInherit)) - inheritanceFlags |= AccessControlEntryFlags.ContainerInherit; - if (flags.HasFlag(SystemSecurity.AceFlags.ObjectInherit)) - inheritanceFlags |= AccessControlEntryFlags.ObjectInherit; - if (flags.HasFlag(SystemSecurity.AceFlags.NoPropagateInherit)) - inheritanceFlags |= AccessControlEntryFlags.NoPropagateInherit; - if (flags.HasFlag(SystemSecurity.AceFlags.InheritOnly)) - inheritanceFlags |= AccessControlEntryFlags.InheritOnly; - - aces.Add(new(isFolder, pszSid.ToString(), type, accessMaskFlags, isInherited, inheritanceFlags)); - } - finally - { - Marshal.FreeHGlobal((nint)pszSid.Value); - } - } - - // Initialize with proper data - acl = new AccessControlList(path, isFolder, principal, isValidAcl); - - // Set access control entries - foreach (var ace in aces) - acl.AccessControlEntries.Add(ace); - - return WIN32_ERROR.ERROR_SUCCESS; - } - finally - { - Marshal.FreeHGlobal((nint)pSecurityDescriptor.Value); - } - } - - /// - public FileSecurityResult AddAce(string szPath, bool isFolder, string szSid) - => AddAceCore(szPath, isFolder, szSid).ToFileSecurityResult(); - - private unsafe WIN32_ERROR AddAceCore(string szPath, bool isFolder, string szSid) - { - // Get DACL for the specified object - var result = PInvoke.GetNamedSecurityInfo( - szPath, - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION, - out _, - out _, - out ACL* pDACL, - out _, - out var pSecurityDescriptor); - - if (result is not WIN32_ERROR.ERROR_SUCCESS) - return result; - - try - { - if (pDACL == null) - return WIN32_ERROR.ERROR_INVALID_ACL; - - ACL_SIZE_INFORMATION aclSizeInfo = default; - bool bResult = PInvoke.GetAclInformation( - pDACL, - &aclSizeInfo, - (uint)Marshal.SizeOf(), - ACL_INFORMATION_CLASS.AclSizeInformation); - if (!bResult) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - PSID pSid = default; - fixed (char* cSid = szSid) - { - if (!PInvoke.ConvertStringSidToSid(new PCWSTR(cSid), &pSid)) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - } - - try - { - var sidLength = (uint)new SecurityIdentifier(szSid).BinaryLength; - var cbNewDACL = checked( - aclSizeInfo.AclBytesInUse + - (uint)Marshal.SizeOf() + - sidLength - - (uint)sizeof(uint)); - var pNewDACL = (ACL*)PInvoke.LocalAlloc(LOCAL_ALLOC_FLAGS.LPTR, (nuint)cbNewDACL); - if (pNewDACL == null) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - try - { - if (!PInvoke.InitializeAcl(pNewDACL, cbNewDACL, ACE_REVISION.ACL_REVISION)) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - // Copy ACEs from the old DACL - for (uint dwAceIndex = 0; dwAceIndex < aclSizeInfo.AceCount; dwAceIndex++) - { - ACCESS_ALLOWED_ACE* pTempAce = default; - if (!PInvoke.GetAce(pDACL, dwAceIndex, (void**)&pTempAce)) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - if (!PInvoke.AddAce(pNewDACL, ACE_REVISION.ACL_REVISION, uint.MaxValue, pTempAce, pTempAce->Header.AceSize)) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - } - - bResult = PInvoke.AddAccessAllowedAceEx( - pNewDACL, - ACE_REVISION.ACL_REVISION, - isFolder ? ACE_FLAGS.CONTAINER_INHERIT_ACE | ACE_FLAGS.OBJECT_INHERIT_ACE : ACE_FLAGS.NO_INHERITANCE, - 0x20000000 | 0x80000000 /* GENERIC_EXECUTE and GENERIC_READ */, - pSid); - if (!bResult) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - fixed (char* cPath = szPath) - { - return PInvoke.SetNamedSecurityInfo( - new PWSTR(cPath), - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION, - new PSID((void*)0), - new PSID((void*)0), - pNewDACL); - } - } - finally - { - Marshal.FreeHGlobal((nint)pNewDACL); - } - } - finally - { - Marshal.FreeHGlobal((nint)pSid.Value); - } - } - finally - { - Marshal.FreeHGlobal((nint)pSecurityDescriptor.Value); - } - } - - /// - public FileSecurityResult DeleteAce(string szPath, uint dwAceIndex) - => DeleteAceCore(szPath, dwAceIndex).ToFileSecurityResult(); - - private unsafe WIN32_ERROR DeleteAceCore(string szPath, uint dwAceIndex) - { - // Get DACL for the specified object - var result = PInvoke.GetNamedSecurityInfo( - szPath, - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION, - out _, - out _, - out ACL* pDACL, - out _, - out var pSecurityDescriptor); - - if (result is not WIN32_ERROR.ERROR_SUCCESS) - return result; - - try - { - if (pDACL == null) - return WIN32_ERROR.ERROR_INVALID_ACL; - - // Remove an ACE - if (!PInvoke.DeleteAce(pDACL, dwAceIndex)) - return (WIN32_ERROR)Marshal.GetLastPInvokeError(); - - fixed (char* cPath = szPath) - { - return PInvoke.SetNamedSecurityInfo( - new PWSTR(cPath), - SE_OBJECT_TYPE.SE_FILE_OBJECT, - OBJECT_SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | OBJECT_SECURITY_INFORMATION.PROTECTED_DACL_SECURITY_INFORMATION, - new PSID((void*)0), - new PSID((void*)0), - pDACL); - } - } - finally - { - Marshal.FreeHGlobal((nint)pSecurityDescriptor.Value); - } - } - } -} diff --git a/src/Files.App/Services/Storage/StorageTrashBinService.Windows.cs b/src/Files.App/Services/Storage/StorageTrashBinService.Windows.cs deleted file mode 100644 index 9dac95734efe..000000000000 --- a/src/Files.App/Services/Storage/StorageTrashBinService.Windows.cs +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.IO; -using System.Runtime.InteropServices; -using System.Security.Principal; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Services -{ - /// - public class StorageTrashBinService : IStorageTrashBinService - { - /// - public RecycleBinWatcher Watcher { get; private set; } = new(); - - /// - public async Task> GetAllRecycleBinFoldersAsync() - { - return (await Win32Helper.GetShellFolderAsync(Constants.UserEnvironmentPaths.RecycleBinPath, false, true, 0, int.MaxValue)).Enumerate; - } - - /// - public (bool HasRecycleBin, long NumItems, long BinSize) QueryRecycleBin(string drive = "") - { - SHQUERYRBINFO queryBinInfo = default; - queryBinInfo.cbSize = (uint)Marshal.SizeOf(queryBinInfo); - - var hRes = PInvoke.SHQueryRecycleBin(drive, ref queryBinInfo); - return hRes == HRESULT.S_OK - ? (true, queryBinInfo.i64NumItems, queryBinInfo.i64Size) - : (false, 0, 0); - } - - /// - public ulong GetSize() - { - return (ulong)QueryRecycleBin().BinSize; - } - - /// - public bool HasItems() - { - var sid = WindowsIdentity.GetCurrent().User?.Value; - if (string.IsNullOrEmpty(sid)) - return false; - - foreach (DriveInfo drive in DriveInfo.GetDrives()) - { - if (!drive.IsReady || drive.DriveType == System.IO.DriveType.Network) - continue; - - string recyclePath = Path.Combine(drive.RootDirectory.FullName, "$RECYCLE.BIN", sid); - if (!Directory.Exists(recyclePath)) - continue; - - try - { - var files = Directory.EnumerateFiles(recyclePath, "$I*", SearchOption.TopDirectoryOnly); - if (files.Any()) - return true; - } - catch (UnauthorizedAccessException) - { - } - catch (IOException) - { - } - } - - return false; - } - - /// - public bool IsUnderTrashBin(string? path) - { - return - !string.IsNullOrWhiteSpace(path) && - RegexHelpers.RecycleBinPath().IsMatch(path); - } - - /// - public async Task CanGoTrashBin(string? path) - { - if (string.IsNullOrEmpty(path) || - path.StartsWith(@"\\?\", StringComparison.Ordinal)) - return false; - - var result = await FileOperationsHelpers.TestRecycleAsync(path.Split('|')); - - return - result.Item1 &= result.Item2 is not null && - result.Item2.Items.All(x => x.Succeeded); - } - - /// - public bool EmptyTrashBin() - { - IShellView? recycleBinView = null; - try - { - PInvoke.SHGetKnownFolderItem(FOLDERID.FOLDERID_RecycleBinFolder, KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, null, out IShellItem recycleBinFolder).ThrowOnFailure(); - recycleBinFolder.BindToHandler(null, PInvoke.BHID_SFViewObject, out recycleBinView).ThrowOnFailure(); - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Failed to create the Recycle Bin shell view."); - } - - // TODO: Use IFileOperation instead of its wrapper for the operation status to be reported. - var fRes = PInvoke.SHEmptyRecycleBin( - new(), - string.Empty, - 0x00000001 | 0x00000002 /* SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI */) - .Succeeded; - - if (fRes) - { - PInvoke.SHUpdateRecycleBinIcon(); - - if (recycleBinView is not null) - { - HRESULT hr = recycleBinView.Refresh(); - if (hr.Failed) - App.Logger.LogWarning("Failed to refresh the Recycle Bin shell view. HRESULT: 0x{HResult:X8}", hr.Value); - } - } - - return fRes; - } - - /// - public async Task RestoreAllTrashesAsync() - { - return await STATask.Run(() => - { - try - { - RestoreAllTrashesInternal(); - - return true; - } - catch - { - return false; - } - }, App.Logger); - } - - private unsafe bool RestoreAllTrashesInternal() - { - // Get IShellItem for Recycle Bin folder - HRESULT hr = PInvoke.SHGetKnownFolderItem(FOLDERID.FOLDERID_RecycleBinFolder, KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, null, out IShellItem pRecycleBinFolderShellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - // Get IEnumShellItems for Recycle Bin folder - hr = pRecycleBinFolderShellItem.BindToHandler(null, PInvoke.BHID_EnumItems, out IEnumShellItems? pEnumShellItems); - if (hr.ThrowIfFailedOnDebug().Failed || pEnumShellItems is null) - return false; - - // Initialize how to perform the operation - hr = PInvoke.CoCreateInstance(typeof(FileOperation).GUID, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IFileOperation? pFileOperation); - if (hr.ThrowIfFailedOnDebug().Failed || pFileOperation is null) - return false; - - hr = pFileOperation.SetOperationFlags(FILEOPERATION_FLAGS.FOF_NO_UI); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - hr = pFileOperation.SetOwnerWindow(new(MainWindow.Instance.WindowHandle)); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - IShellItem[] shellItems = new IShellItem[1]; - while (pEnumShellItems.Next(1, shellItems, null) == HRESULT.S_OK) - { - IShellItem shellItem = shellItems[0]; - - if (shellItem is not IShellItem2 shellItem2) - continue; - - hr = PInvoke.PSGetPropertyKeyFromName("System.Recycle.DeletedFrom", out var originalPathPropertyKey); - if (hr.Failed) - continue; - - hr = shellItem2.GetString(originalPathPropertyKey, out var szOriginalPath); - if (hr.Failed) - continue; - - try - { - // Get IShellItem of the original path - hr = PInvoke.SHCreateItemFromParsingName(szOriginalPath.ToString(), null, out IShellItem originalPathShellItem); - if (hr.Failed) - continue; - - // Define the shell item to restore - hr = pFileOperation.MoveItem(shellItem, originalPathShellItem, null!, null!); - } - finally - { - PInvoke.CoTaskMemFree(szOriginalPath); - } - } - - // Perform - hr = pFileOperation.PerformOperations(); - if (hr.ThrowIfFailedOnDebug().Failed) - return false; - - // Reset the icon - PInvoke.SHUpdateRecycleBinIcon(); - - return true; - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsCompatibilityService.cs b/src/Files.App/Services/Windows/WindowsCompatibilityService.cs deleted file mode 100644 index e9aa5eb91212..000000000000 --- a/src/Files.App/Services/Windows/WindowsCompatibilityService.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; - -namespace Files.App.Services -{ - /// - public sealed class WindowsCompatibilityService : IWindowsCompatibilityService - { - private readonly string _registrySubPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers"; - - /// - public WindowsCompatibilityOptions GetCompatibilityOptionsForPath(string filePath) - { - try - { - // Get the key - using var compatKey = Registry.CurrentUser.OpenSubKey(_registrySubPath); - if (compatKey is null) - return new(); - - // Get the value for the specified path - var stringOptions = (string?)compatKey.GetValue(filePath, null); - - return WindowsCompatibilityOptions.FromString(stringOptions); - } - catch (Exception) - { - return new(); - } - } - - /// - public bool SetCompatibilityOptionsForPath(string filePath, WindowsCompatibilityOptions options) - { - var stringOptions = options.ToString(); - var registryPath = Win32Helper.ToPowerShellStringLiteral($@"HKCU:\{_registrySubPath}"); - var propertyName = Win32Helper.ToPowerShellStringLiteral(filePath); - - // Remove old one if new one is valid - if (string.IsNullOrEmpty(stringOptions) || stringOptions == "~") - { - return Win32Helper.RunPowershellCommand( - $"Remove-ItemProperty -Path {registryPath} -Name {propertyName} | Out-Null", - PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - } - - // Set the new one - return Win32Helper.RunPowershellCommand( - $"New-ItemProperty -Path {registryPath} -Name {propertyName} -Value {Win32Helper.ToPowerShellStringLiteral(stringOptions)} -PropertyType String -Force | Out-Null", - PowerShellExecutionOptions.Elevated | PowerShellExecutionOptions.Hidden); - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsDialogService.cs b/src/Files.App/Services/Windows/WindowsDialogService.cs deleted file mode 100644 index f08f339fffc4..000000000000 --- a/src/Files.App/Services/Windows/WindowsDialogService.cs +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.NetworkManagement.WNet; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; - -namespace Files.App.Services -{ - /// - public sealed class CommonDialogService : ICommonDialogService - { - /// - public unsafe bool Open_FileOpenDialog(nint hWnd, bool pickFoldersOnly, string[] filters, Environment.SpecialFolder defaultFolder, out string filePath, Guid? clientGuid = null) - { - filePath = string.Empty; - - try - { - HRESULT hr = PInvoke.CoCreateInstance(typeof(FileOpenDialog).GUID, null, CLSCTX.CLSCTX_INPROC_SERVER, out IFileOpenDialog? pDialog); - - // Handle COM creation failure gracefully - if (hr.Failed || pDialog is null) - { - App.Logger.LogError("Failed to create IFileOpenDialog COM object. HRESULT: 0x{0:X8}", hr.Value); - return false; - } - - SetFileTypes(pDialog, filters); - - // Get the default shell folder (My Computer) - IShellItem? pDefaultFolderShellItem = null; - hr = PInvoke.SHCreateItemFromParsingName(Environment.GetFolderPath(defaultFolder), null, out IShellItem defaultFolderShellItem); - - // Handle shell item creation failure gracefully - if (hr.Failed) - { - App.Logger.LogWarning("Failed to create shell item for default folder '{0}'. HRESULT: 0x{1:X8}. Dialog will open without default folder.", defaultFolder, hr.Value); - // Continue without setting default folder rather than failing completely - } - else - { - pDefaultFolderShellItem = defaultFolderShellItem; - } - - // Folder picker - if (pickFoldersOnly) - pDialog.SetOptions(FILEOPENDIALOGOPTIONS.FOS_PICKFOLDERS); - - // Persist dialog state (including the last browsed folder) under the caller's GUID - if (clientGuid is { } guid) - pDialog.SetClientGuid(in guid); - - // Set the default folder to open in the dialog (only if creation succeeded) - if (pDefaultFolderShellItem is not null) - { - // SetFolder forces the dialog to always open at this folder, which would override the persisted state - if (clientGuid is null) - pDialog.SetFolder(pDefaultFolderShellItem); - - pDialog.SetDefaultFolder(pDefaultFolderShellItem); - } - - // Show the dialog - hr = pDialog.Show(new HWND(hWnd)); - if (hr.Value == unchecked((int)0x800704C7)) // HRESULT_FROM_WIN32(ERROR_CANCELLED) - return false; - - // Handle dialog show failure gracefully - if (hr.Failed) - { - App.Logger.LogError("Failed to show FileSaveDialog. HRESULT: 0x{0:X8}", hr.Value); - return false; - } - - // Get the file that user chose - pDialog.GetResult(out IShellItem pResultShellItem); - if (pResultShellItem is null) - throw new COMException("FileOpenDialog returned invalid shell item."); - pResultShellItem.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out var lpFilePath); - try - { - filePath = lpFilePath.ToString(); - } - finally - { - PInvoke.CoTaskMemFree(lpFilePath); - } - - return true; - } - catch (COMException comEx) - { - App.Logger.LogError(comEx, "COM failure while opening FileOpenDialog. HRESULT: 0x{0:X8}", comEx.HResult); - return false; - } - catch (Exception ex) - { - App.Logger.LogError(ex, "Unexpected error while opening FileOpenDialog."); - return false; - } - } - - /// - public unsafe bool Open_FileSaveDialog(nint hWnd, bool pickFoldersOnly, string[] filters, Environment.SpecialFolder defaultFolder, out string filePath) - { - filePath = string.Empty; - - try - { - HRESULT hr = PInvoke.CoCreateInstance(typeof(FileSaveDialog).GUID, null, CLSCTX.CLSCTX_INPROC_SERVER, out IFileSaveDialog? pDialog); - - // Handle COM creation failure gracefully - if (hr.Failed || pDialog is null) - { - App.Logger.LogError("Failed to create IFileSaveDialog COM object. HRESULT: 0x{0:X8}", hr.Value); - return false; - } - - SetFileTypes(pDialog, filters); - - // Get the default shell folder (My Computer) - IShellItem? pDefaultFolderShellItem = null; - hr = PInvoke.SHCreateItemFromParsingName(Environment.GetFolderPath(defaultFolder), null, out IShellItem defaultFolderShellItem); - - // Handle shell item creation failure gracefully - if (hr.Failed) - { - App.Logger.LogWarning("Failed to create shell item for default folder '{0}'. HRESULT: 0x{1:X8}. Dialog will open without default folder.", defaultFolder, hr.Value); - // Continue without setting default folder rather than failing completely - } - else - { - pDefaultFolderShellItem = defaultFolderShellItem; - } - - // Folder picker - if (pickFoldersOnly) - pDialog.SetOptions(FILEOPENDIALOGOPTIONS.FOS_PICKFOLDERS); - - // Set the default folder to open in the dialog (only if creation succeeded) - if (pDefaultFolderShellItem is not null) - { - pDialog.SetFolder(pDefaultFolderShellItem); - pDialog.SetDefaultFolder(pDefaultFolderShellItem); - } - - // Show the dialog - hr = pDialog.Show(new HWND(hWnd)); - if (hr.Value == unchecked((int)0x800704C7)) // HRESULT_FROM_WIN32(ERROR_CANCELLED) - return false; - - // Handle dialog show failure gracefully - if (hr.Failed) - { - App.Logger.LogError("Failed to show FileSaveDialog. HRESULT: 0x{0:X8}", hr.Value); - return false; - } - - // Get the file that user chose - pDialog.GetResult(out IShellItem pResultShellItem); - if (pResultShellItem is null) - throw new COMException("FileSaveDialog returned invalid shell item."); - pResultShellItem.GetDisplayName(SIGDN.SIGDN_FILESYSPATH, out var lpFilePath); - try - { - filePath = lpFilePath.ToString(); - } - finally - { - PInvoke.CoTaskMemFree(lpFilePath); - } - - return true; - } - catch (COMException comEx) - { - App.Logger.LogError(comEx, "COM failure while opening FileSaveDialog. HRESULT: 0x{0:X8}", comEx.HResult); - return false; - } - catch (Exception ex) - { - App.Logger.LogError(ex, "Unexpected error while opening FileSaveDialog."); - return false; - } - } - - private static unsafe void SetFileTypes(IFileDialog dialog, string[] filters) - { - if (filters.Length == 0 || filters.Length % 2 != 0) - return; - - var filterSpecs = new COMDLG_FILTERSPEC[filters.Length / 2]; - var allocations = new nint[filters.Length]; - try - { - for (var filterIndex = 0; filterIndex < filterSpecs.Length; filterIndex++) - { - var sourceIndex = filterIndex * 2; - allocations[sourceIndex] = Marshal.StringToHGlobalUni(filters[sourceIndex]); - allocations[sourceIndex + 1] = Marshal.StringToHGlobalUni(filters[sourceIndex + 1]); - filterSpecs[filterIndex] = new COMDLG_FILTERSPEC - { - pszName = (char*)allocations[sourceIndex], - pszSpec = (char*)allocations[sourceIndex + 1], - }; - } - - dialog.SetFileTypes(filterSpecs); - } - finally - { - foreach (var allocation in allocations) - Marshal.FreeHGlobal(allocation); - } - } - - /// - public unsafe bool Open_NetworkConnectionDialog(nint hWnd, bool hideRestoreConnectionCheckBox = false, bool persistConnectionAtLogon = false, bool readOnlyPath = false, string? remoteNetworkName = null, bool useMostRecentPath = false) - { - if (useMostRecentPath && !string.IsNullOrEmpty(remoteNetworkName)) - throw new ArgumentException($"{nameof(useMostRecentPath)} cannot be set to true if {nameof(remoteNetworkName)} has a value."); - - NETRESOURCEW netResource = default; - CONNECTDLGSTRUCTW connectDlgOptions = default; - WIN32_ERROR res = default; - - if (hideRestoreConnectionCheckBox) - connectDlgOptions.dwFlags |= CONNECTDLGSTRUCT_FLAGS.CONNDLG_HIDE_BOX; - if (persistConnectionAtLogon) - connectDlgOptions.dwFlags |= CONNECTDLGSTRUCT_FLAGS.CONNDLG_PERSIST; - if (useMostRecentPath) - connectDlgOptions.dwFlags |= CONNECTDLGSTRUCT_FLAGS.CONNDLG_USE_MRU; - if (readOnlyPath && !string.IsNullOrEmpty(remoteNetworkName)) - connectDlgOptions.dwFlags |= CONNECTDLGSTRUCT_FLAGS.CONNDLG_RO_PATH; - - fixed (char* pszRemoteName = remoteNetworkName) - { - netResource.dwType = NET_RESOURCE_TYPE.RESOURCETYPE_DISK; - netResource.lpRemoteName = pszRemoteName; - - connectDlgOptions.cbStructure = (uint)sizeof(CONNECTDLGSTRUCTW); - connectDlgOptions.hwndOwner = new(hWnd); - connectDlgOptions.lpConnRes = &netResource; - - res = PInvoke.WNetConnectionDialog1W(ref connectDlgOptions); - } - - // User canceled - if ((uint)res == unchecked((uint)-1)) - return false; - - // Unexpected error happened - if (res is not WIN32_ERROR.NO_ERROR) - throw new Win32Exception("Failed to process the network connection dialog successfully."); - - return true; - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsIniService.cs b/src/Files.App/Services/Windows/WindowsIniService.cs deleted file mode 100644 index 0ab2d5a0802f..000000000000 --- a/src/Files.App/Services/Windows/WindowsIniService.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Services -{ - /// - public sealed class WindowsIniService : IWindowsIniService - { - /// - public List GetData(string filePath) - { - if (!SystemIO.File.Exists(filePath)) - return []; - - var lines = Enumerable.Empty().ToList(); - - try - { - lines = SystemIO.File.ReadLines(filePath) - .Where(line => !line.StartsWith(';') && !string.IsNullOrEmpty(line)) - .ToList(); - } - catch (Exception ex) when (ex is UnauthorizedAccessException || ex is SystemIO.FileNotFoundException || ex is SystemIO.IOException) - { - return []; - } - - // Get section line indexes directly to handle duplicate section names - List sectionLineIndexes = []; - for (int i = 0; i < lines.Count; i++) - { - if (lines[i].StartsWith('[') && lines[i].EndsWith(']')) - sectionLineIndexes.Add(i); - } - - List dataItems = []; - - for (int index = 0; index < sectionLineIndexes.Count; index++) - { - var sectionIndex = sectionLineIndexes[index]; - - var count = - index + 1 == sectionLineIndexes.Count - ? lines.Count - sectionIndex - 1 - : sectionLineIndexes[index + 1] - sectionIndex - 1; - - if (count <= 0) - continue; - - var range = lines.GetRange(sectionIndex + 1, count); - - var sectionName = lines[sectionLineIndexes[index]].TrimStart('[').TrimEnd(']'); - - // Read data - var parameters = range - // Split the lines into key and value - .Select(line => line.Split('=')) - // Validate - .Where(parts => parts.Length == 2) - // Group by key to avoid duplicates - .GroupBy(parts => parts[0].Trim()) - // Gather as dictionary - .ToDictionary(partsGroup => partsGroup.Key, partsGroup => partsGroup.Last()[1].Trim()); - - dataItems.Add(new() - { - SectionName = sectionName, - Parameters = parameters, - }); - } - - return dataItems; - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsJumpListService.cs b/src/Files.App/Services/Windows/WindowsJumpListService.cs deleted file mode 100644 index 91700ca6ba81..000000000000 --- a/src/Files.App/Services/Windows/WindowsJumpListService.cs +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.IO; -using Windows.UI.StartScreen; - -namespace Files.App.Services -{ - public sealed class WindowsJumpListService : IWindowsJumpListService - { - private const string JumpListRecentGroupHeader = "ms-resource:///Resources/JumpListRecentGroupHeader"; - private const string JumpListPinnedGroupHeader = "ms-resource:///Resources/JumpListPinnedGroupHeader"; - - // SaveAsync throws ArgumentException ("Maximum number of items exceeded") once the list grows past - // the shell's cap, so the recent group must stay bounded. The taskbar displays at most ~13 entries. - private const int MaxRecentItemsCount = 20; - - public async Task InitializeAsync() - { - try - { - App.QuickAccessManager.UpdateQuickAccessWidget -= UpdateQuickAccessWidget_Invoked; - App.QuickAccessManager.UpdateQuickAccessWidget += UpdateQuickAccessWidget_Invoked; - - await RefreshPinnedFoldersAsync(); - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - } - - public async Task AddFolderAsync(string path) - { - try - { - if (JumpList.IsSupported()) - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - // Saving to jumplist may fail randomly with error: ERROR_UNABLE_TO_REMOVE_REPLACED - // In that case app should just catch the error and proceed as usual - if (instance is not null) - { - AddFolder(path, JumpListRecentGroupHeader, instance); - await instance.SaveAsync(); - } - } - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - } - - public async Task> GetFoldersAsync() - { - if (JumpList.IsSupported()) - { - try - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - return instance.Items.Select(item => item.Arguments).ToList(); - } - catch - { - return []; - } - } - else - { - return []; - } - } - - public async Task RefreshPinnedFoldersAsync() - { - try - { - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; - - if (JumpList.IsSupported()) - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work with Files UWP. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - if (instance is null) - return; - - var itemsToRemove = instance.Items.Where(x => string.Equals(x.GroupName, JumpListPinnedGroupHeader, StringComparison.OrdinalIgnoreCase)).ToList(); - itemsToRemove.ForEach(x => instance.Items.Remove(x)); - App.QuickAccessManager.Model.PinnedFolders.ForEach(x => AddFolder(x, JumpListPinnedGroupHeader, instance)); - await instance.SaveAsync(); - } - } - catch - { - } - finally - { - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - SafetyExtensions.IgnoreExceptions(() => App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true); - } - } - - public async Task RemoveFolderAsync(string path) - { - if (JumpList.IsSupported()) - { - try - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - var itemToRemove = instance.Items.Where(x => x.Arguments == path).Select(x => x).FirstOrDefault(); - instance.Items.Remove(itemToRemove); - await instance.SaveAsync(); - } - catch { } - } - } - - private void AddFolder(string path, string group, JumpList instance) - { - if (instance is not null) - { - string? displayName = null; - - if (path.StartsWith("\\\\SHELL", StringComparison.OrdinalIgnoreCase)) - displayName = Strings.ThisPC.GetLocalizedResource(); - - if (path.EndsWith('\\')) - { - var drivesViewModel = Ioc.Default.GetRequiredService(); - - // Jumplist item argument can't end with a slash so append a character that can't exist in a directory name to support listing drives. - var drive = drivesViewModel.Drives.FirstOrDefault(drive => drive.Id == path); - if (drive is null) - return; - - displayName = (drive as DriveItem)?.Text; - path += '?'; - } - - if (displayName is null) - { - if (path.Equals(Constants.UserEnvironmentPaths.DesktopPath, StringComparison.OrdinalIgnoreCase)) - displayName = "ms-resource:///Resources/Desktop"; - else if (path.Equals(Constants.UserEnvironmentPaths.DownloadsPath, StringComparison.OrdinalIgnoreCase)) - displayName = "ms-resource:///Resources/Downloads"; - else if (path.Equals(Constants.UserEnvironmentPaths.NetworkFolderPath, StringComparison.OrdinalIgnoreCase)) - displayName = Strings.Network.GetLocalizedResource(); - else if (path.Equals(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - displayName = Strings.RecycleBin.GetLocalizedResource(); - else if (path.Equals(Constants.UserEnvironmentPaths.MyComputerPath, StringComparison.OrdinalIgnoreCase)) - displayName = Strings.ThisPC.GetLocalizedResource(); - else if (App.LibraryManager.TryGetLibrary(path, out var library)) - { - var libName = Path.GetFileNameWithoutExtension(library.Path); - displayName = libName switch - { - "Documents" or "Pictures" or "Music" or "Videos" => $"ms-resource:///Resources/{libName}",// Use localized name - _ => library.Text,// Use original name - }; - } - else - displayName = Path.GetFileName(path); - } - - var jumplistItem = Windows.UI.StartScreen.JumpListItem.CreateWithArguments(path, displayName); - jumplistItem.Description = jumplistItem.Arguments ?? string.Empty; - jumplistItem.GroupName = group; - jumplistItem.Logo = new Uri("ms-appx:///Assets/FolderIcon.png"); - - if (string.Equals(group, JumpListRecentGroupHeader, StringComparison.OrdinalIgnoreCase)) - { - // Keep newer items at the top. - instance.Items.Remove(instance.Items.FirstOrDefault(x => x.Arguments.Equals(path, StringComparison.OrdinalIgnoreCase))); - instance.Items.Insert(0, jumplistItem); - - var excessRecentItems = instance.Items - .Where(x => string.Equals(x.GroupName, JumpListRecentGroupHeader, StringComparison.OrdinalIgnoreCase)) - .Skip(MaxRecentItemsCount) - .ToList(); - - foreach (var item in excessRecentItems) - instance.Items.Remove(item); - } - else - { - var pinnedItemsCount = instance.Items.Count(x => x.GroupName == JumpListPinnedGroupHeader); - instance.Items.Insert(pinnedItemsCount, jumplistItem); - } - } - } - - private async void UpdateQuickAccessWidget_Invoked(object? sender, ModifyQuickAccessEventArgs e) - { - await RefreshPinnedFoldersAsync(); - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsQuickAccessService.cs b/src/Files.App/Services/Windows/WindowsQuickAccessService.cs deleted file mode 100644 index 4a479cc0dea1..000000000000 --- a/src/Files.App/Services/Windows/WindowsQuickAccessService.cs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Services -{ - internal sealed class QuickAccessService : IQuickAccessService - { - // Quick access shell folder (::{679f85cb-0220-4080-b29b-5540cc05aab6}) contains recent files - // which are unnecessary for getting pinned folders, so we use frequent places shell folder instead. - private readonly static string guid = "::{3936e9e4-d92c-4eee-a85a-bc16d5ea0819}"; - - public async Task> GetPinnedFoldersAsync() - { - var result = (await Win32Helper.GetShellFolderAsync(guid, false, true, 0, int.MaxValue, "System.Home.IsPinned")).Enumerate - .Where(link => link.IsFolder); - return result; - } - - public Task PinToSidebarAsync(string folderPath) => PinToSidebarAsync(new[] { folderPath }); - - public Task PinToSidebarAsync(string[] folderPaths) => PinToSidebarAsync(folderPaths, true); - - private async Task PinToSidebarAsync(string[] folderPaths, bool doUpdateQuickAccessWidget) - { - foreach (string folderPath in folderPaths) - { - // make sure that the item has not yet been pinned - // the verb 'pintohome' is for both adding and removing - if (!IsItemPinned(folderPath)) - await ContextMenu.InvokeVerb("pintohome", folderPath); - } - - await App.QuickAccessManager.Model.LoadAsync(); - if (doUpdateQuickAccessWidget) - App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, true)); - } - - public Task UnpinFromSidebarAsync(string folderPath) => UnpinFromSidebarAsync(new[] { folderPath }); - - public Task UnpinFromSidebarAsync(string[] folderPaths) => UnpinFromSidebarAsync(folderPaths, true); - - private async Task UnpinFromSidebarAsync(string[] folderPaths, bool doUpdateQuickAccessWidget) - { - ShellFileItem[] shellItems = [.. await GetPinnedFoldersAsync()]; - - if (folderPaths.Length == 0) - folderPaths = shellItems - .Where(link => (bool?)link.Properties["System.Home.IsPinned"] ?? false) - .Select(link => link.FilePath!).ToArray(); - - foreach (ShellFileItem shellItem in shellItems) - { - string pathStr = shellItem.FilePath - ?? throw new InvalidOperationException("The Windows Shell Home namespace returned an item without a path."); - bool shouldUnpin = folderPaths.Contains(pathStr); - -#if WINDOWS - if (ShellStorageFolder.IsShellPath(pathStr)) - { - var folder = await ShellStorageFolder.FromPathAsync(pathStr); - var path = folder?.Path; - - shouldUnpin = shouldUnpin || path is not null && - (folderPaths.Contains(path) || - (path.StartsWith(@"\\SHELL\\") && folderPaths.Any(x => x.StartsWith(@"\\SHELL\\")))); - } - -#endif - if (!shouldUnpin) - continue; - - byte[] pidl = shellItem.PIDL - ?? throw new InvalidOperationException("The Windows Shell Home namespace returned an item without a PIDL."); - - var result = await STATask.Run(() => - { - using var item = ShellItem.Open(new ShellPidl(pidl)); - using var windowsFile = new WindowsFile(item.IShellItem); - return windowsFile.TryInvokeContextMenuVerbs(["unpinfromhome", "remove"], true); - }, App.Logger); - - if (result.Failed) - { - await App.QuickAccessManager.Model.LoadAsync(); - return false; - } - } - - await App.QuickAccessManager.Model.LoadAsync(); - if (doUpdateQuickAccessWidget) - App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, false)); - - return true; - } - - public bool IsItemPinned(string folderPath) - { - return App.QuickAccessManager.Model.PinnedFolders.Contains(folderPath); - } - - public async Task SaveAsync(string[] items) - { - if (Equals(items, App.QuickAccessManager.Model.PinnedFolders.ToArray())) - return; - - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; - - // Unpin every item that is below this index and then pin them all in order - if (!await UnpinFromSidebarAsync([], false)) - { - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true; - return; - } - - await PinToSidebarAsync(items, false); - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true; - - App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(items, true) - { - Reorder = true - }); - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsRecentItemsService.cs b/src/Files.App/Services/Windows/WindowsRecentItemsService.cs deleted file mode 100644 index 5f71024b8373..000000000000 --- a/src/Files.App/Services/Windows/WindowsRecentItemsService.cs +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.Collections.Specialized; -using System.IO; -using System.Text; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.SystemServices; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Services -{ - /// - public class WindowsRecentItemsService : IWindowsRecentItemsService - { - // Dependency injections - - private readonly IFoldersSettingsService FoldersSettingsService = Ioc.Default.GetRequiredService(); - - // Fields - - private readonly SystemIO.FileSystemWatcher? _watcher; - - // Properties - - private readonly List _RecentFiles = []; - /// - public IReadOnlyList RecentFiles - { - get - { - lock (_RecentFiles) - return _RecentFiles.ToList().AsReadOnly(); - } - } - - private readonly List _RecentFolders = []; - /// - public IReadOnlyList RecentFolders - { - get - { - lock (_RecentFolders) - return _RecentFolders.ToList().AsReadOnly(); - } - } - - // Events - - /// - public event EventHandler? RecentFilesChanged; - - /// - public event EventHandler? RecentFoldersChanged; - - // Constructor - - public WindowsRecentItemsService() - { - var automaticDestinationsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Recent), "AutomaticDestinations"); - - // Only create the file system watcher if the AutomaticDestinations directory exists - if (Directory.Exists(automaticDestinationsPath)) - { - _watcher = new() - { - Path = automaticDestinationsPath, - Filter = "5f7b5f1e01b83767.automaticDestinations-ms", - NotifyFilter = SystemIO.NotifyFilters.DirectoryName | SystemIO.NotifyFilters.FileName | SystemIO.NotifyFilters.LastWrite, - }; - - _watcher.Changed += Watcher_Changed; - _watcher.Deleted += Watcher_Changed; - _watcher.EnableRaisingEvents = true; - } - // If the directory doesn't exist, _watcher remains null and the service will function without file system monitoring - } - - // Methods - - /// - public async Task UpdateRecentFilesAsync() - { - return await Task.Run(() => - { - return UpdateRecentItems(false); - }); - } - - /// - public async Task UpdateRecentFoldersAsync() - { - return await Task.Run(() => - { - return UpdateRecentItems(true); - }); - } - - /// - public unsafe bool Add(string path) - { - try - { - fixed (char* cPath = path) - PInvoke.SHAddToRecentDocs((uint)SHARD.SHARD_PATHW, cPath); - - return true; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - return false; - } - } - - /// - public unsafe bool Remove(RecentItem item) - { - try - { - HRESULT hr = item.ShellItem!.BindToHandler(null, PInvoke.BHID_SFUIObject, out IContextMenu? pContextMenu); - if (hr.Failed || pContextMenu is null) - return false; - - HMENU hMenu = PInvoke.CreatePopupMenu(); - hr = pContextMenu.QueryContextMenu(hMenu, 0, 1, 0x7FFF, PInvoke.CMF_OPTIMIZEFORINVOKE); - - // Initialize invocation info - CMINVOKECOMMANDINFO cmi = default; - cmi.cbSize = (uint)sizeof(CMINVOKECOMMANDINFO); - cmi.nShow = (int)SHOW_WINDOW_CMD.SW_HIDE; - - // Unpin the item - fixed (byte* pVerb1 = Encoding.ASCII.GetBytes("remove"), - pVerb2 = Encoding.ASCII.GetBytes("unpinfromhome"), - pVerb3 = Encoding.ASCII.GetBytes("removefromhome")) - { - // Try unpin files - cmi.lpVerb = new(pVerb1); - hr = pContextMenu.InvokeCommand(cmi); - if (hr == HRESULT.S_OK) - return true; - - // Try unpin folders - cmi.lpVerb = new(pVerb2); - hr = pContextMenu.InvokeCommand(cmi); - if (hr == HRESULT.S_OK) - return true; - - // NOTE: - // There seems to be an issue with unpinfromhome where some shell folders - // won't be removed via unpinfromhome verb. - // Try unpin folders again - cmi.lpVerb = new(pVerb3); - hr = pContextMenu.InvokeCommand(cmi); - if (hr == HRESULT.S_OK) - return true; - } - - return true; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - return false; - } - } - - /// - public unsafe bool Clear() - { - try - { - PInvoke.SHAddToRecentDocs((uint)SHARD.SHARD_PIDL, null); - - return true; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - return false; - } - } - - private unsafe bool UpdateRecentItems(bool isFolder) - { - try - { - HRESULT hr = default; - - string szFolderShellPath = - isFolder - ? "Shell:::{22877A6D-37A1-461A-91B0-DBDA5AAEBC99}" // Recent Places folder (recent folders) - : "Shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}"; // Quick Access folder (recent files) - - // Get IShellItem of the shell folder - hr = PInvoke.SHCreateItemFromParsingName(szFolderShellPath, null, out IShellItem pFolderShellItem); - if (hr.Failed) - return false; - - // Get IEnumShellItems of the quick access shell folder - hr = pFolderShellItem.BindToHandler(null, PInvoke.BHID_EnumItems, out IEnumShellItems? pEnumShellItems); - if (hr.Failed || pEnumShellItems is null) - return false; - - // Enumerate recent items and populate the list - int index = 0; - List recentItems = []; - IShellItem[] pShellItems = new IShellItem[1]; - while (pEnumShellItems.Next(1, pShellItems, null) == HRESULT.S_OK) - { - IShellItem shellItem = pShellItems[0]; - - // Get top 20 items - if (index is 20) - break; - - // Exclude folders, but keep archives (ZIP/7z/RAR) which the shell reports as both folder and stream. - if (shellItem.GetAttributes(SFGAO_FLAGS.SFGAO_FOLDER | SFGAO_FLAGS.SFGAO_STREAM, out var attribute).Succeeded && - (attribute & SFGAO_FLAGS.SFGAO_FOLDER) == SFGAO_FLAGS.SFGAO_FOLDER && - (attribute & SFGAO_FLAGS.SFGAO_STREAM) == 0) - continue; - - // Get the target path - shellItem.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out var szDisplayName); - var targetPath = szDisplayName.ToString(); - PInvoke.CoTaskMemFree(szDisplayName.Value); - - // Get the display name - shellItem.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY, out szDisplayName); - var fileName = szDisplayName.ToString(); - PInvoke.CoTaskMemFree(szDisplayName.Value); - - // Strip the file extension except when the file name only contains extension (e.g. ".gitignore") - if (!FoldersSettingsService.ShowFileExtensions && - SystemIO.Path.GetFileNameWithoutExtension(fileName) is string fileNameWithoutExtension) - fileName = string.IsNullOrEmpty(fileNameWithoutExtension) ? SystemIO.Path.GetFileName(fileName) : fileNameWithoutExtension; - - // Get the date last modified - DateTime lastModified = DateTime.MinValue; - - if (shellItem is IShellItem2 shellItem2 && - PInvoke.PSGetPropertyKeyFromName("System.DateModified", out var propertyKey).Succeeded) - { - hr = shellItem2.GetString(propertyKey, out var szPropertyValue); - if (hr.Succeeded) - { - if (!DateTime.TryParse(szPropertyValue.ToString(), out lastModified)) - lastModified = DateTime.MinValue; - - PInvoke.CoTaskMemFree(szPropertyValue); - } - } - - recentItems.Add(new() - { - Path = targetPath, - Name = fileName, - ShellItem = shellItem, - LastModified = lastModified, - }); - - index++; - } - - if (recentItems.Count is 0) - return false; - - var snapshot = isFolder ? RecentFolders : RecentFiles; - - if (isFolder) - { - lock (_RecentFolders) - { - _RecentFolders.Clear(); - _RecentFolders.AddRange(recentItems); - } - } - else - { - lock (_RecentFiles) - { - _RecentFiles.Clear(); - _RecentFiles.AddRange(recentItems); - } - } - - var eventArgs = GetChangedActionEventArgs(snapshot, recentItems); - - if (isFolder) - RecentFoldersChanged?.Invoke(this, eventArgs); - else - RecentFilesChanged?.Invoke(this, eventArgs); - - return true; - } - catch - { - return false; - } - } - - private void Watcher_Changed(object sender, SystemIO.FileSystemEventArgs e) - { - _ = UpdateRecentFilesAsync(); - _ = UpdateRecentFoldersAsync(); - } - - private NotifyCollectionChangedEventArgs GetChangedActionEventArgs(IReadOnlyList oldItems, IList newItems) - { - if (newItems.Count - oldItems.Count is 1) - { - var differences = newItems.Except(oldItems); - if (differences.Take(2).Count() == 1) - return new(NotifyCollectionChangedAction.Add, newItems.First()); - } - else if (oldItems.Count - newItems.Count is 1) - { - var differences = oldItems.Except(newItems); - if (differences.Take(2).Count() == 1) - { - for (int i = 0; i < oldItems.Count; i++) - { - if (i >= newItems.Count || !newItems[i].Equals(oldItems[i])) - return new(NotifyCollectionChangedAction.Remove, oldItems[i], index: i); - } - } - } - else if (newItems.Count == oldItems.Count) - { - var differences = oldItems.Except(newItems); - if (differences.Any()) - return new(NotifyCollectionChangedAction.Reset); - - // First diff from reversed is the designated item - for (int i = oldItems.Count - 1; i >= 0; i--) - { - if (!oldItems[i].Equals(newItems[i])) - return new(NotifyCollectionChangedAction.Move, oldItems[i], index: 0, oldIndex: i); - } - } - - return new(NotifyCollectionChangedAction.Reset); - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsSecurityService.cs b/src/Files.App/Services/Windows/WindowsSecurityService.cs deleted file mode 100644 index 5256ea823c4e..000000000000 --- a/src/Files.App/Services/Windows/WindowsSecurityService.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -namespace Files.App.Services -{ - /// - public sealed class WindowsSecurityService : IWindowsSecurityService - { - /// - public unsafe bool IsAppElevated() - { - var identity = System.Security.Principal.WindowsIdentity.GetCurrent(); - var principal = new System.Security.Principal.WindowsPrincipal(identity); - return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator); - } - - /// - public unsafe bool CanDragAndDrop() - { - return !IsAppElevated(); - } - - /// - public bool IsElevationRequired(string? path) - { - if (string.IsNullOrEmpty(path)) - return false; - - return Win32PInvoke.IsElevationRequired(path); - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsShellService.cs b/src/Files.App/Services/Windows/WindowsShellService.cs deleted file mode 100644 index 69da5b4e9755..000000000000 --- a/src/Files.App/Services/Windows/WindowsShellService.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Services -{ - /// - internal sealed class AddItemService : IAddItemService - { - private List? _cached; - - public async Task InitializeAsync() - { - _cached = await ShellNewEntryExtensions.GetNewContextMenuEntries(); - } - - public List? GetEntries() - { - return _cached; - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsStartMenuService.cs b/src/Files.App/Services/Windows/WindowsStartMenuService.cs deleted file mode 100644 index 4ff2b4027663..000000000000 --- a/src/Files.App/Services/Windows/WindowsStartMenuService.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Windows.UI.StartScreen; - -namespace Files.App.Services -{ - /// - internal sealed class StartMenuService : IStartMenuService - { - [Obsolete("See IStartMenuService for further information.")] - public bool IsPinned(string itemPath) - { - var tileId = GetNativeTileId(itemPath); - return SecondaryTile.Exists(tileId); - } - - /// - public Task IsPinnedAsync(IStorable storable) - { - var tileId = GetNativeTileId(storable.Id); - var exists = SecondaryTile.Exists(tileId); - - return Task.FromResult(exists); - } - - /// - public async Task PinAsync(IStorable storable, string? displayName = null) - { - var tileId = GetNativeTileId(storable.Id); - displayName ??= storable.Name; - - try - { - var path150x150 = new Uri("ms-appx:///Assets/tile-0-300x300.png"); - var path71x71 = new Uri("ms-appx:///Assets/tile-0-250x250.png"); - - var tile = new SecondaryTile( - tileId, - displayName, - storable.Id, - path150x150, - TileSize.Square150x150) - { - VisualElements = - { - Square71x71Logo = path71x71, - ShowNameOnSquare150x150Logo = true - } - }; - - WinRT.Interop.InitializeWithWindow.Initialize(tile, MainWindow.Instance.WindowHandle); - - await tile.RequestCreateAsync(); - } - catch (Exception e) - { - Debug.WriteLine(tileId); - Debug.WriteLine(e.ToString()); - } - - } - - /// - public async Task UnpinAsync(IStorable storable) - { - var startScreen = StartScreenManager.GetDefault(); - var tileId = GetNativeTileId(storable.Id); - - await startScreen.TryRemoveSecondaryTileAsync(tileId); - } - - private static string GetNativeTileId(string id) - { - // Remove symbols because windows doesn't like them in the ID, and will blow up - var str = $"folder-{new string(id.Where(c => char.IsLetterOrDigit(c)).ToArray())}"; - - // If the id string is too long, Windows will throw an error, so remove every other character - if (str.Length > 64) - str = new string(str.Where((_, i) => i % 2 == 0).ToArray()); - - return str; - } - } -} diff --git a/src/Files.App/Services/Windows/WindowsWallpaperService.cs b/src/Files.App/Services/Windows/WindowsWallpaperService.cs deleted file mode 100644 index bd5be966e96e..000000000000 --- a/src/Files.App/Services/Windows/WindowsWallpaperService.cs +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Storage; -using Windows.System.UserProfile; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; - -namespace Files.App.Services -{ - /// - public sealed class WindowsWallpaperService : IWindowsWallpaperService - { - /// - public unsafe void SetDesktopWallpaper(string szPath) - { - // Instantiate IDesktopWallpaper - HRESULT hr = PInvoke.CoCreateInstance(typeof(DesktopWallpaper).GUID, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IDesktopWallpaper? pDesktopWallpaper); - if (hr.Failed || pDesktopWallpaper is null) - return; - - // Get total count of all available monitors - hr = pDesktopWallpaper.GetMonitorDevicePathCount(out var dwMonitorCount); - - fixed (char* pszPath = szPath) - { - PWSTR pMonitorId = default; - - // Set the selected image file as wallpaper for all available monitors - for (uint dwIndex = 0u; dwIndex < dwMonitorCount; dwIndex++) - { - // Set the wallpaper - hr = pDesktopWallpaper.GetMonitorDevicePathAt(dwIndex, out pMonitorId); - hr = pDesktopWallpaper.SetWallpaper(pMonitorId.ToString(), szPath); - PInvoke.CoTaskMemFree(pMonitorId); - - pMonitorId = default; - } - } - } - - /// - public unsafe void SetDesktopSlideshow(string[] aszPaths) - { - // Instantiate IDesktopWallpaper - HRESULT hr = PInvoke.CoCreateInstance(typeof(DesktopWallpaper).GUID, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IDesktopWallpaper? pDesktopWallpaper); - if (hr.Failed || pDesktopWallpaper is null) - return; - - uint dwCount = (uint)aszPaths.Length; - ITEMIDLIST** ppItemIdList = stackalloc ITEMIDLIST*[aszPaths.Length]; - - // Get an array of PIDL from the selected image files - for (uint dwIndex = 0u; dwIndex < dwCount; dwIndex++) - ppItemIdList[dwIndex] = PInvoke.ILCreateFromPath(aszPaths[dwIndex]); - - // Get an IShellItemArray from the array of the PIDL - hr = PInvoke.SHCreateShellItemArrayFromIDLists(dwCount, ppItemIdList, out IShellItemArray pShellItemArray); - - // Release the allocated PIDL - for (uint dwIndex = 0u; dwIndex < dwCount; dwIndex++) - PInvoke.CoTaskMemFree((void*)ppItemIdList[dwIndex]); - - // Set the slideshow and its position - hr = pDesktopWallpaper.SetSlideshow(pShellItemArray); - hr = pDesktopWallpaper.SetPosition(DESKTOP_WALLPAPER_POSITION.DWPOS_FILL); - } - - /// - public async Task SetLockScreenWallpaper(string szPath) - { - IStorageFile sourceFile = await StorageFile.GetFileFromPathAsync(szPath); - await LockScreen.SetImageFileAsync(sourceFile); - } - } -} diff --git a/src/Files.App/UserControls/FilePreviews/CodePreview.xaml b/src/Files.App/UserControls/FilePreviews/CodePreview.xaml deleted file mode 100644 index affc28524ab5..000000000000 --- a/src/Files.App/UserControls/FilePreviews/CodePreview.xaml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - diff --git a/src/Files.App/UserControls/FilePreviews/CodePreview.xaml.cs b/src/Files.App/UserControls/FilePreviews/CodePreview.xaml.cs deleted file mode 100644 index 3e5350ed0ec4..000000000000 --- a/src/Files.App/UserControls/FilePreviews/CodePreview.xaml.cs +++ /dev/null @@ -1,55 +0,0 @@ -using ColorCode; -using Files.App.ViewModels.Previews; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; - -// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 - -namespace Files.App.UserControls.FilePreviews -{ - public sealed partial class CodePreview : UserControl - { - private CodePreviewViewModel ViewModel { get; set; } - - public CodePreview(CodePreviewViewModel model) - { - ViewModel = model; - InitializeComponent(); - } - - private void RenderDocument() - { - if (codeView is not null) - { - codeView.Blocks?.Clear(); - - if (ViewModel.Item.FileExtension is ".css" or ".scss") - { - // Some complex CSS files can make ColorCode parsing very slow and freeze the preview pane. - // Use our lightweight renderer for CSS/SCSS to keep preview responsive while preserving highlighting. - CssPreviewRenderer.Render(codeView, ViewModel.TextValue ?? string.Empty, ActualTheme == ElementTheme.Dark); - return; - } - - var formatter = new RichTextBlockFormatter(ActualTheme); - formatter.FormatRichTextBlock(ViewModel.TextValue!, ViewModel.CodeLanguage!, codeView); - } - } - - private void UserControl_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e) - { - RenderDocument(); - } - - private void UserControl_ActualThemeChanged(Microsoft.UI.Xaml.FrameworkElement sender, object args) - { - try - { - RenderDocument(); - } - catch (Exception) - { - } - } - } -} diff --git a/src/Files.App/UserControls/FilePreviews/DesktopTextPreview.xaml.cs b/src/Files.App/UserControls/FilePreviews/DesktopTextPreview.xaml.cs index 9f49b072a8dc..f060d2af1223 100644 --- a/src/Files.App/UserControls/FilePreviews/DesktopTextPreview.xaml.cs +++ b/src/Files.App/UserControls/FilePreviews/DesktopTextPreview.xaml.cs @@ -1,4 +1,3 @@ -#if !WINDOWS // Copyright (c) Files Community // Licensed under the MIT License. @@ -85,4 +84,3 @@ private void BuildContent() } } -#endif diff --git a/src/Files.App/UserControls/FilePreviews/MarkdownPreview.xaml b/src/Files.App/UserControls/FilePreviews/MarkdownPreview.xaml deleted file mode 100644 index 94bd9c1b3f05..000000000000 --- a/src/Files.App/UserControls/FilePreviews/MarkdownPreview.xaml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/src/Files.App/UserControls/FilePreviews/MarkdownPreview.xaml.cs b/src/Files.App/UserControls/FilePreviews/MarkdownPreview.xaml.cs deleted file mode 100644 index 03a769ae9650..000000000000 --- a/src/Files.App/UserControls/FilePreviews/MarkdownPreview.xaml.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using CommunityToolkit.Labs.WinUI.MarkdownTextBlock; -using Files.App.ViewModels.Previews; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Media; -using Windows.System; -using WinRT; - -namespace Files.App.UserControls.FilePreviews -{ - public sealed partial class MarkdownPreview : UserControl - { - private MarkdownPreviewViewModel ViewModel { get; set; } - - [DynamicWindowsRuntimeCast(typeof(Brush))] - public MarkdownPreview(MarkdownPreviewViewModel model) - { - ViewModel = model; - InitializeComponent(); - - // Workaround for https://github.com/CommunityToolkit/Labs-Windows/issues/611 - PreviewMarkdownTextBlock.Config = MarkdownConfig.Default; - PreviewMarkdownTextBlock.Config.Themes.HeadingForeground = (Brush)Application.Current.Resources["TextControlForeground"]; - } - - private async void PreviewMarkdownTextBlock_OnLinkClicked(object sender, CommunityToolkit.Labs.WinUI.MarkdownTextBlock.LinkClickedEventArgs e) - { - await Launcher.LaunchUriAsync(e.Uri); - } - } -} diff --git a/src/Files.App/UserControls/FilePreviews/PreviewTextRenderer.cs b/src/Files.App/UserControls/FilePreviews/PreviewTextRenderer.cs index 06ca1fc3a740..aa05680be9e4 100644 --- a/src/Files.App/UserControls/FilePreviews/PreviewTextRenderer.cs +++ b/src/Files.App/UserControls/FilePreviews/PreviewTextRenderer.cs @@ -1,4 +1,3 @@ -#if !WINDOWS // Copyright (c) Files Community // Licensed under the MIT License. @@ -316,4 +315,3 @@ private static void AddInlines(InlineCollection target, ContainerInline? contain } } -#endif diff --git a/src/Files.App/UserControls/FilePreviews/ShellPreview.xaml b/src/Files.App/UserControls/FilePreviews/ShellPreview.xaml deleted file mode 100644 index 86784ab288d7..000000000000 --- a/src/Files.App/UserControls/FilePreviews/ShellPreview.xaml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - diff --git a/src/Files.App/UserControls/FilePreviews/ShellPreview.xaml.cs b/src/Files.App/UserControls/FilePreviews/ShellPreview.xaml.cs deleted file mode 100644 index 06d601982b59..000000000000 --- a/src/Files.App/UserControls/FilePreviews/ShellPreview.xaml.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Previews; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Windows.Foundation; -using Windows.Win32.Foundation; -using WinRT; - -namespace Files.App.UserControls.FilePreviews -{ - public sealed partial class ShellPreview : UserControl - { - private ShellPreviewViewModel ViewModel { get; set; } - - public ShellPreview(ShellPreviewViewModel model) - { - ViewModel = model; - - InitializeComponent(); - } - - [DynamicWindowsRuntimeCast(typeof(FrameworkElement))] - private void PreviewHost_Loaded(object sender, RoutedEventArgs e) - { - ViewModel.LoadPreview(contentPresenter); - ViewModel.SizeChanged(GetPreviewSize()); - - if (XamlRoot.Content is FrameworkElement element) - { - element.SizeChanged += PreviewHost_SizeChanged; - element.PointerEntered += PreviewHost_PointerEntered; - } - } - - private void PreviewHost_SizeChanged(object sender, SizeChangedEventArgs e) - { - ViewModel.SizeChanged(GetPreviewSize()); - } - - private RECT GetPreviewSize() - { - var source = contentPresenter.TransformToVisual(XamlRoot.Content); - var physicalSize = contentPresenter.RenderSize; - var physicalPos = source.TransformPoint(new Point(0, 0)); - var scale = XamlRoot.RasterizationScale; - var result = RECT.FromXYWH( - (int)(physicalPos.X * scale + 0.5), - (int)(physicalPos.Y * scale + 0.5), - (int)(physicalSize.Width * scale + 0.5), - (int)(physicalSize.Height * scale + 0.5)); - - return result; - } - - [DynamicWindowsRuntimeCast(typeof(FrameworkElement))] - private void PreviewHost_Unloaded(object sender, RoutedEventArgs e) - { - if (XamlRoot.Content is FrameworkElement element) - { - element.SizeChanged -= PreviewHost_SizeChanged; - element.PointerEntered -= PreviewHost_PointerEntered; - } - - ViewModel.UnloadPreview(); - } - - private void PreviewHost_PointerEntered(object sender, Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e) - { - ViewModel.PointerEntered(ReferenceEquals(sender, contentPresenter)); - } - - // Lets callers tear the preview host down right away instead of waiting on the Unloaded event - public void UnloadPreview() - => ViewModel.UnloadPreview(); - } -} diff --git a/src/Files.App/UserControls/FilePreviews/TextPreview.xaml b/src/Files.App/UserControls/FilePreviews/TextPreview.xaml deleted file mode 100644 index fcf63c5947ce..000000000000 --- a/src/Files.App/UserControls/FilePreviews/TextPreview.xaml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Files.App/UserControls/FilePreviews/TextPreview.xaml.cs b/src/Files.App/UserControls/FilePreviews/TextPreview.xaml.cs deleted file mode 100644 index 800b611a077c..000000000000 --- a/src/Files.App/UserControls/FilePreviews/TextPreview.xaml.cs +++ /dev/null @@ -1,21 +0,0 @@ -#if WINDOWS -using Files.App.ViewModels.Previews; -using Microsoft.UI.Xaml.Controls; - -// To learn more about WinUI, the WinUI project structure, -// and more about our project templates, see: http://aka.ms/winui-project-info. - -namespace Files.App.UserControls.FilePreviews -{ - public sealed partial class TextPreview : UserControl - { - public TextPreview(TextPreviewViewModel viewModel) - { - ViewModel = viewModel; - InitializeComponent(); - } - - public TextPreviewViewModel ViewModel { get; set; } - } -} -#endif diff --git a/src/Files.App/UserControls/NavigationToolbar.xaml.cs b/src/Files.App/UserControls/NavigationToolbar.xaml.cs index fd914695ddd1..84d89ed5a41e 100644 --- a/src/Files.App/UserControls/NavigationToolbar.xaml.cs +++ b/src/Files.App/UserControls/NavigationToolbar.xaml.cs @@ -349,74 +349,6 @@ private async void BreadcrumbBar_ItemDropDownFlyoutOpening(object sender, Breadc { if (e.IsRootItem) { -#if WINDOWS - IHomeFolder homeFolder = new HomeFolder(); - IContentPageContext contentPageContext = Ioc.Default.GetRequiredService(); - - e.Flyout.Items.Add(new MenuFlyoutHeaderItem() { Text = Strings.QuickAccess.GetLocalizedResource() }); - - await foreach (var storable in homeFolder.GetQuickAccessFolderAsync()) - { - if (storable is not IWindowsStorable windowsStorable) - continue; - - var flyoutItem = new MenuFlyoutItem() - { - Text = windowsStorable.GetDisplayName(Windows.Win32.UI.Shell.SIGDN.SIGDN_PARENTRELATIVEFORUI), - DataContext = windowsStorable.GetDisplayName(Windows.Win32.UI.Shell.SIGDN.SIGDN_DESKTOPABSOLUTEPARSING), - Icon = new FontIcon() { Glyph = "\uE8B7" }, // As a placeholder - }; - - e.Flyout.Items.Add(flyoutItem); - - windowsStorable.TryGetThumbnail((int)(16f * App.AppModel.AppWindowDPI), Windows.Win32.UI.Shell.SIIGBF.SIIGBF_ICONONLY, out var thumbnailData); - flyoutItem.Icon = new ImageIcon() { Source = await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => thumbnailData.ToBitmapAsync(), Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal) }; - - windowsStorable.Dispose(); - - flyoutItem.Click += (sender, args) => - { - // NOTE: We should not pass a path string but pass the storable object itself in the future. - var path = flyoutItem.DataContext as string - ?? throw new InvalidOperationException("The breadcrumb item does not have a navigation path."); - var shellPage = contentPageContext.ShellPage - ?? throw new InvalidOperationException("There is no active shell page for breadcrumb navigation."); - shellPage.NavigateToPath(path); - }; - } - - e.Flyout.Items.Add(new MenuFlyoutHeaderItem() { Text = Strings.Drives.GetLocalizedResource() }); - - await foreach (var storable in homeFolder.GetLogicalDrivesAsync()) - { - if (storable is not IWindowsStorable windowsStorable) - continue; - - var flyoutItem = new MenuFlyoutItem() - { - Text = windowsStorable.GetDisplayName(Windows.Win32.UI.Shell.SIGDN.SIGDN_PARENTRELATIVEFORUI), - DataContext = windowsStorable.GetDisplayName(Windows.Win32.UI.Shell.SIGDN.SIGDN_DESKTOPABSOLUTEPARSING), - Icon = new FontIcon() { Glyph = "\uE8B7" }, // As a placeholder - }; - - e.Flyout.Items.Add(flyoutItem); - - windowsStorable.TryGetThumbnail((int)(16f * App.AppModel.AppWindowDPI), Windows.Win32.UI.Shell.SIIGBF.SIIGBF_ICONONLY, out var thumbnailData); - flyoutItem.Icon = new ImageIcon() { Source = await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => thumbnailData.ToBitmapAsync(), Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal) }; - - windowsStorable.Dispose(); - - flyoutItem.Click += (sender, args) => - { - // NOTE: We should not pass a path string but pass the storable object itself in the future. - var path = flyoutItem.DataContext as string - ?? throw new InvalidOperationException("The breadcrumb item does not have a navigation path."); - var shellPage = contentPageContext.ShellPage - ?? throw new InvalidOperationException("There is no active shell page for breadcrumb navigation."); - shellPage.NavigateToPath(path); - }; - } -#else IHomeFolder homeFolder = Ioc.Default.GetRequiredService().HomeFolder; IContentPageContext contentPageContext = Ioc.Default.GetRequiredService(); @@ -444,7 +376,6 @@ async Task AddItemsAsync(string header, IAsyncEnumerable storabl await AddItemsAsync(Strings.QuickAccess.GetLocalizedResource(), homeFolder.GetQuickAccessFolderAsync()); await AddItemsAsync(Strings.Drives.GetLocalizedResource(), homeFolder.GetLogicalDrivesAsync()); -#endif return; } diff --git a/src/Files.App/UserControls/Pane/ShelfPane.xaml.cs b/src/Files.App/UserControls/Pane/ShelfPane.xaml.cs index 52d52a0b702c..31459e25f346 100644 --- a/src/Files.App/UserControls/Pane/ShelfPane.xaml.cs +++ b/src/Files.App/UserControls/Pane/ShelfPane.xaml.cs @@ -7,10 +7,6 @@ using System.Runtime.InteropServices; using System.Windows.Input; using Windows.ApplicationModel.DataTransfer; -#if WINDOWS -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; -#endif using WinRT; using DragEventArgs = Microsoft.UI.Xaml.DragEventArgs; using Visibility = Microsoft.UI.Xaml.Visibility; @@ -43,11 +39,7 @@ private async void Shelf_Drop(object sender, DragEventArgs e) return; // Get items -#if WINDOWS - var storageService = Ioc.Default.GetRequiredService(); -#else var resolver = Ioc.Default.GetRequiredService(); -#endif var storageItems = (await FilesystemHelpers.GetDraggedStorageItems(e.DataView)).ToArray(); // Add to list @@ -57,17 +49,8 @@ private async void Shelf_Drop(object sender, DragEventArgs e) if (ItemsSource.Any(x => x.Inner.Id == item.Path)) continue; -#if WINDOWS - var storable = item switch - { - StorageFileWithPath => (IStorableChild?)await storageService.TryGetFileAsync(item.Path), - StorageFolderWithPath => (IStorableChild?)await storageService.TryGetFolderAsync(item.Path), - _ => null - }; -#else var resolved = await resolver.TryGetAsync(item.Path); var storable = resolved.Item as IStorableChild; -#endif if (storable is null) continue; @@ -85,28 +68,8 @@ private void ListView_DragItemsStarting(object sender, DragItemsStartingEventArg if (paths.Length is 0) return; -#if WINDOWS - var items = new List(paths.Length); - try - { - items.AddRange(paths.Select(path => new ShellItem(path))); - IDataObject dataObject = ShellDataObject.Create(items); - e.Data.Properties["Files_ActionBinder"] = "Files_ShelfBinder"; - e.Data.As().SetDataObject(dataObject).ThrowOnFailure(); - } - catch (COMException exception) - { - Debug.WriteLine(exception); - } - finally - { - foreach (ShellItem item in items) - item.Dispose(); - } -#else e.Data.Properties["Files_ActionBinder"] = "Files_ShelfBinder"; Files.App.Services.Desktop.DesktopFileDragHelper.StartExternalDrag(paths); -#endif } private void ShelfItemsList_RightTapped(object sender, Microsoft.UI.Xaml.Input.RightTappedRoutedEventArgs e) diff --git a/src/Files.App/UserControls/StatusCenter/SpeedGraph.cs b/src/Files.App/UserControls/StatusCenter/SpeedGraph.cs index d008d0af795e..f393cff92a9e 100644 --- a/src/Files.App/UserControls/StatusCenter/SpeedGraph.cs +++ b/src/Files.App/UserControls/StatusCenter/SpeedGraph.cs @@ -1,8 +1,4 @@ -#if WINDOWS -using Microsoft.Graphics.Canvas.Geometry; -#else using SkiaSharp; -#endif using Microsoft.UI.Composition; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; @@ -216,23 +212,6 @@ void UpdateGraph() CompositionPath CreatePathFromPoints() { -#if WINDOWS - using var pathBuilder = new CanvasPathBuilder(null); - pathBuilder.BeginFigure(0f, height); - for (int i = 0; i < Points.Count; i++) - { - if (Points[i].Y > highestValue) - highestValue = Points[i].Y; - // no smooth curve for now. a little ugly but maybe for the best performance-wise, we'll see before this gets merged - pathBuilder.AddLine(width * Points[i].X / 100f, YValue(Points[i].Y)); - } - // little extra part so that steep lines don't get cut off - pathBuilder.AddLine(width * Points[^1].X / 100f + 2, YValue(Points[^1].Y)); - pathBuilder.AddLine(width * Points[^1].X / 100f + 2, height); - pathBuilder.EndFigure(CanvasFigureLoop.Closed); - var path = new CompositionPath(CanvasGeometry.CreatePath(pathBuilder)); - return path; -#else // Uno Skia: build an SKPath and wrap it in a composition geometry source var skPath = new SKPath(); skPath.MoveTo(0f, height); @@ -250,7 +229,6 @@ CompositionPath CreatePathFromPoints() var sourceType = typeof(CompositionPath).Assembly.GetType("Microsoft.UI.Composition.SkiaGeometrySource2D")!; var source = (Windows.Graphics.IGeometrySource2D)Activator.CreateInstance(sourceType, skPath)!; return new CompositionPath(source); -#endif } void SetGraphColors() diff --git a/src/Files.App/UserControls/TabBar/TabBar.Linux.cs b/src/Files.App/UserControls/TabBar/TabBar.Linux.cs index 3dc5d506aad5..55d3eecb60be 100644 --- a/src/Files.App/UserControls/TabBar/TabBar.Linux.cs +++ b/src/Files.App/UserControls/TabBar/TabBar.Linux.cs @@ -12,7 +12,6 @@ public sealed partial class TabBar { private void InitializeLinuxCaptionButtons() { -#if !WINDOWS if (!OperatingSystem.IsLinux()) return; @@ -23,10 +22,8 @@ private void InitializeLinuxCaptionButtons() Unloaded += LinuxCaptionButtons_Unloaded; UpdateLinuxCaptionButtons(); _ = NavigationHelpers.UpdateInstancePropertiesAsync(Items.ElementAtOrDefault(App.AppModel.TabStripSelectedIndex)?.NavigationParameter?.NavigationParameter); -#endif } -#if !WINDOWS private void LinuxCaptionButtons_Unloaded(object sender, RoutedEventArgs e) => MainWindow.Instance.LinuxChromeChanged -= LinuxChromeChanged; @@ -44,13 +41,10 @@ private void UpdateLinuxCaptionButtons() LinuxMaximizeIcon.Glyph = window.IsLinuxWindowMaximized ? "\uE923" : "\uE922"; UpdateTitleBarInsets(); } -#endif private void ClientSideDecorationsMenuItem_Click(object sender, RoutedEventArgs e) { -#if !WINDOWS MainWindow.Instance.SetClientSideDecorations(ClientSideDecorationsMenuItem.IsChecked); -#endif } private void MinimizeWindow_Click(object sender, RoutedEventArgs e) @@ -61,9 +55,7 @@ private void MinimizeWindow_Click(object sender, RoutedEventArgs e) private void MaximizeWindow_Click(object sender, RoutedEventArgs e) { -#if !WINDOWS MainWindow.Instance.ToggleLinuxWindowMaximize(); -#endif } private void CloseWindow_Click(object sender, RoutedEventArgs e) => MainWindow.Instance.Close(); diff --git a/src/Files.App/UserControls/TabBar/TabBar.xaml.cs b/src/Files.App/UserControls/TabBar/TabBar.xaml.cs index 4facb0f41206..3979da15dfc4 100644 --- a/src/Files.App/UserControls/TabBar/TabBar.xaml.cs +++ b/src/Files.App/UserControls/TabBar/TabBar.xaml.cs @@ -490,7 +490,6 @@ private void DragAreaRectangle_Loaded(object sender, RoutedEventArgs e) private void UpdateTitleBarInsets() { -#if !WINDOWS if (OperatingSystem.IsLinux()) { RightPaddingColumn.Width = new(MainWindow.Instance.HasClientSideDecorations ? 146 : 8); @@ -502,7 +501,6 @@ private void UpdateTitleBarInsets() } return; } -#endif var titleBarInset = ((AppLanguageHelper.IsPreferredLanguageRtl ? MainWindow.Instance.AppWindow.TitleBar.LeftInset : MainWindow.Instance.AppWindow.TitleBar.RightInset) / DragAreaRectangle.XamlRoot.RasterizationScale) + 40; diff --git a/src/Files.App/UserControls/Toolbar.xaml.Windows.cs b/src/Files.App/UserControls/Toolbar.xaml.Windows.cs deleted file mode 100644 index db89ba65be0e..000000000000 --- a/src/Files.App/UserControls/Toolbar.xaml.Windows.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using CommunityToolkit.WinUI; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Automation; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Input; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Media.Imaging; -using System.IO; -using Windows.Win32.UI.WindowsAndMessaging; -using WinRT; -using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue; -using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; -using FlyoutPlacementMode = Microsoft.UI.Xaml.Controls.Primitives.FlyoutPlacementMode; - -namespace Files.App.UserControls -{ - public sealed partial class Toolbar : UserControl - { - private OpenWithMenu? openWithMenu; - - private async Task PopulateOpenWithFlyoutAsync(MenuFlyout flyout) - { - var requestId = ++openWithFlyoutRequestId; - - flyout.Items.Add(new MenuFlyoutItem - { - Text = Strings.Loading.GetLocalizedResource(), - IsEnabled = false, - }); - - openWithMenu?.Dispose(); - openWithMenu = null; - - OpenWithMenu? loadedOpenWithMenu = null; - if (PageContext.SelectedItems.Count is 1 && PageContext.SelectedItem?.ItemPath is string path) - loadedOpenWithMenu = await OpenWithMenu.GetForFileAsync(path); - - if (requestId != openWithFlyoutRequestId) - { - loadedOpenWithMenu?.Dispose(); - return; - } - - openWithMenu = loadedOpenWithMenu; - - flyout.Items.Clear(); - - if (openWithMenu is not null) - { - foreach (var item in openWithMenu.Items.Where(x => x.Type is MENU_ITEM_TYPE.MFT_STRING && !string.IsNullOrWhiteSpace(x.Label))) - flyout.Items.Add(await CreateOpenWithMenuItemAsync(openWithMenu, item)); - } - - if (flyout.Items.Count == 0) - flyout.Items.Add(CreateChooseAnotherAppMenuItem()); - } - - private static async Task CreateOpenWithMenuItemAsync(OpenWithMenu menu, Win32ContextMenuItem entry) - { - MenuFlyoutItem item; - if (entry.Icon is { Length: > 0 }) - { - using var ms = new MemoryStream(entry.Icon); - var image = new BitmapImage(); - await image.SetSourceAsync(ms.AsRandomAccessStream()); - item = new MenuFlyoutItemWithImage { BitmapIcon = image }; - } - else - { - item = new MenuFlyoutItem(); - } - - item.Text = entry.Label; - item.Command = new AsyncRelayCommand(async () => await menu.InvokeItem(entry.ID)); - - return item; - } - } -} diff --git a/src/Files.App/UserControls/Toolbar.xaml.cs b/src/Files.App/UserControls/Toolbar.xaml.cs index 970e48a9a394..a1233280cdb7 100644 --- a/src/Files.App/UserControls/Toolbar.xaml.cs +++ b/src/Files.App/UserControls/Toolbar.xaml.cs @@ -64,9 +64,6 @@ private void Toolbar_Unloaded(object sender, RoutedEventArgs e) UserSettingsService.AppearanceSettingsService.PropertyChanged -= AppearanceSettings_PropertyChanged; if (editTagsMenu is not null) editTagsMenu.TagsChanged -= EditTagsMenu_TagsChanged; -#if WINDOWS - openWithMenu?.Dispose(); -#endif ++openWithFlyoutRequestId; } @@ -557,7 +554,6 @@ private async Task PopulateGroupFlyoutAsync(MenuFlyout flyout, CommandGroup grou return; } -#if !WINDOWS if (group is NewItemCommandGroup) { // Same items as the context menu's New submenu @@ -570,14 +566,9 @@ private async Task PopulateGroupFlyoutAsync(MenuFlyout flyout, CommandGroup grou } return; } -#endif foreach (var code in group.Commands) -#if WINDOWS - if (Commands[code] is { Code: not CommandCodes.None } cmd) -#else if (Commands[code] is { Code: not CommandCodes.None, IsExecutable: true } cmd) -#endif flyout.Items.Add(CreateGroupMenuItem(cmd)); if (group is NewItemCommandGroup && ViewModel?.InstanceViewModel.CanCreateFileInPage == true @@ -598,7 +589,6 @@ private async Task PopulateGroupFlyoutAsync(MenuFlyout flyout, CommandGroup grou -#if !WINDOWS private async Task PopulateOpenWithFlyoutAsync(MenuFlyout flyout) { var requestId = ++openWithFlyoutRequestId; @@ -631,7 +621,6 @@ private async Task PopulateOpenWithFlyoutAsync(MenuFlyout flyout) if (flyout.Items.Count == 0) flyout.Items.Add(CreateChooseAnotherAppMenuItem()); } -#endif private MenuFlyoutItem CreateChooseAnotherAppMenuItem() { diff --git a/src/Files.App/Utils/Cloud/CloudDrivesDetector.Windows.cs b/src/Files.App/Utils/Cloud/CloudDrivesDetector.Windows.cs deleted file mode 100644 index 436f9a628e9c..000000000000 --- a/src/Files.App/Utils/Cloud/CloudDrivesDetector.Windows.cs +++ /dev/null @@ -1,376 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; -using System.IO; -using System.Runtime.Versioning; - -namespace Files.App.Utils.Cloud -{ - [SupportedOSPlatform("Windows10.0.10240")] - public sealed class CloudDrivesDetector - { - private readonly static string? programFilesFolder = Environment.GetEnvironmentVariable("ProgramFiles"); - - public static async Task> DetectCloudDrives() - { - var tasks = new Task?>[] - { - SafetyExtensions.IgnoreExceptions(DetectOneDrive, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectSharepoint, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectGenericCloudDrive, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectYandexDisk, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectpCloudDrive, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectNutstoreDrive, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectSeadriveDrive, App.Logger), - SafetyExtensions.IgnoreExceptions(DetectAutodeskDrive, App.Logger), - }; - - var results = await Task.WhenAll(tasks); - - return results - .WhereNotNull() - .SelectMany(providers => providers) - .OrderBy(o => o.ID.ToString()) - .ThenBy(o => o.Name) - .Distinct(); - } - - private static Task> DetectYandexDisk() - { - var results = new List(); - using var yandexKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Yandex\Yandex.Disk.2"); - - var syncedFolder = (string?)yandexKey?.GetValue("RootFolder"); - if (syncedFolder is not null) - { - results.Add(new CloudProvider(CloudProviders.Yandex) - { - Name = $"Yandex Disk", - SyncFolder = syncedFolder, - }); - } - - return Task.FromResult>(results); - } - - private static Task> DetectGenericCloudDrive() - { - var results = new List(); - using var clsidKey = Registry.ClassesRoot.OpenSubKey(@"CLSID"); - using var namespaceKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace"); - using var syncRootManagerKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager"); - - foreach (var subKeyName in namespaceKey?.GetSubKeyNames() ?? []) - { - using var clsidSubKey = SafetyExtensions.IgnoreExceptions(() => clsidKey?.OpenSubKey(subKeyName)); - if (clsidSubKey is not null && (int?)clsidSubKey.GetValue("System.IsPinnedToNameSpaceTree") is 1) - { - using var namespaceSubKey = namespaceKey?.OpenSubKey(subKeyName); - var driveIdentifier = (string?)namespaceSubKey?.GetValue(string.Empty); - if (driveIdentifier is null) - continue; - - var driveType = GetDriveType(driveIdentifier, namespaceSubKey, syncRootManagerKey); - - using var bagKey = clsidSubKey.OpenSubKey(@"Instance\InitPropertyBag"); - var syncedFolder = (string?)bagKey?.GetValue("TargetFolderPath"); - if (syncedFolder is null) - continue; - - // Also works for OneDrive, Box, Dropbox - CloudProviders? cloudProvider = driveType switch - { - "MEGA" => CloudProviders.Mega, - "Nextcloud" => CloudProviders.Nextcloud, - "Jottacloud" => CloudProviders.Jottacloud, - "iCloudDrive" => CloudProviders.AppleCloudDrive, - "iCloudPhotos" => CloudProviders.AppleCloudPhotos, - "Creative Cloud Files" => CloudProviders.AdobeCreativeCloud, - "ownCloud" => CloudProviders.ownCloud, - "ProtonDrive" => CloudProviders.ProtonDrive, - "kDrive" => CloudProviders.kDrive, - "Lucid" => CloudProviders.LucidLink, - "SyncCom" => CloudProviders.SyncDrive, - "MagentaCLOUD" => CloudProviders.MagentaCloud, - _ => null, - }; - - if (cloudProvider is null) - continue; - - var nextCloudValue = (string?)namespaceSubKey?.GetValue(string.Empty); - var clsidDefaultValue = (string?)clsidSubKey?.GetValue(string.Empty); - - using var defaultIconKey = clsidSubKey?.OpenSubKey(@"DefaultIcon"); - var iconPath = (string?)defaultIconKey?.GetValue(string.Empty); - - results.Add(new CloudProvider(cloudProvider.Value) - { - Name = cloudProvider switch - { - CloudProviders.Mega => $"MEGA ({Path.GetFileName(syncedFolder.TrimEnd('\\'))})", - CloudProviders.Nextcloud => !string.IsNullOrEmpty(nextCloudValue) ? nextCloudValue : "Nextcloud", - CloudProviders.Jottacloud => $"Jottacloud", - CloudProviders.AppleCloudDrive => $"iCloud Drive", - CloudProviders.AppleCloudPhotos => $"iCloud Photos", - CloudProviders.AdobeCreativeCloud => $"Creative Cloud Files", - CloudProviders.ownCloud => !string.IsNullOrEmpty(clsidDefaultValue) ? clsidDefaultValue : "ownCloud", - CloudProviders.ProtonDrive => $"Proton Drive", - CloudProviders.kDrive => !string.IsNullOrEmpty(clsidDefaultValue) ? clsidDefaultValue : "kDrive", - CloudProviders.LucidLink => !string.IsNullOrEmpty(clsidDefaultValue) ? clsidDefaultValue : "lucidLink", - CloudProviders.SyncDrive => !string.IsNullOrEmpty(clsidDefaultValue) ? clsidDefaultValue : "Sync", - CloudProviders.MagentaCloud => !string.IsNullOrEmpty(clsidDefaultValue) ? clsidDefaultValue : "MagentaCLOUD", - _ => null - }, - SyncFolder = syncedFolder, - IconData = GetIconData(iconPath) - }); - } - } - - return Task.FromResult>(results); - } - - private static byte[]? GetIconData(string? iconPath) - { - if (string.IsNullOrEmpty(iconPath) || !File.Exists(iconPath)) - return null; - - if (iconPath.EndsWith(".dll") || iconPath.EndsWith(".exe")) - return Win32Helper.ExtractSelectedIconsFromDLL(iconPath, new List() { 32512 }).FirstOrDefault()?.IconData; - - return File.ReadAllBytes(iconPath); - } - - private static Task?> DetectOneDrive() - { - using var oneDriveAccountsKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\OneDrive\Accounts"); - if (oneDriveAccountsKey is null) - { - return Task.FromResult?>(null); - } - - var oneDriveAccounts = new List(); - foreach (var account in oneDriveAccountsKey.GetSubKeyNames()) - { - var accountKeyName = @$"{oneDriveAccountsKey.Name}\{account}"; - var displayName = (string?)Registry.GetValue(accountKeyName, "DisplayName", null); - var userFolder = (string?)Registry.GetValue(accountKeyName, "UserFolder", null); - var accountName = string.IsNullOrWhiteSpace(displayName) ? "OneDrive" : $"OneDrive - {displayName}"; - - if (!string.IsNullOrWhiteSpace(userFolder) && !oneDriveAccounts.Any(x => x.Name == accountName)) - { - oneDriveAccounts.Add(new CloudProvider(CloudProviders.OneDrive) - { - Name = accountName, - SyncFolder = userFolder, - IconData = GetIconData($"Environment.GetEnvironmentVariable(\"ProgramFiles\")\\Microsoft OneDrive\\OneDrive.exe"), - }); - } - } - - return Task.FromResult?>(oneDriveAccounts); - } - - private static Task?> DetectSharepoint() - { - using var oneDriveAccountsKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\OneDrive\Accounts"); - if (oneDriveAccountsKey is null) - { - return Task.FromResult?>(null); - } - - var sharepointAccounts = new List(); - foreach (var account in oneDriveAccountsKey.GetSubKeyNames()) - { - var accountKey = oneDriveAccountsKey.OpenSubKey(account); - if (accountKey is null) - continue; - - var userFolderToExcludeFromResults = (string)accountKey.GetValue("UserFolder", ""); - - var sharePointParentFolders = new List(); - using (var mountPointsKey = accountKey.OpenSubKey("ScopeIdToMountPointPathCache")) - { - if (mountPointsKey is null) - { - continue; - } - - var valueNames = mountPointsKey.GetValueNames(); - foreach (var valueName in valueNames) - { - var directory = (string?)mountPointsKey.GetValue(valueName, null); - if (directory != null && !string.Equals(directory, userFolderToExcludeFromResults, StringComparison.OrdinalIgnoreCase)) - { - var parentFolder = Directory.GetParent(directory); - if (parentFolder != null) - sharePointParentFolders.Add(parentFolder); - } - } - } - - sharePointParentFolders.Sort((left, right) => left.FullName.CompareTo(right.FullName)); - - foreach (var sharePointParentFolder in sharePointParentFolders) - { - string name = $"SharePoint - {sharePointParentFolder.Name}"; - if (!sharepointAccounts.Any(acc => string.Equals(acc.Name, name, StringComparison.OrdinalIgnoreCase))) - { - sharepointAccounts.Add(new CloudProvider(CloudProviders.OneDriveCommercial) - { - Name = name, - SyncFolder = sharePointParentFolder.FullName, - }); - } - } - } - - return Task.FromResult?>(sharepointAccounts); - } - - private static Task> DetectpCloudDrive() - { - var results = new List(); - using var pCloudDriveKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\pCloud"); - - var syncedFolder = (string?)pCloudDriveKey?.GetValue("SyncDrive"); - if (syncedFolder is not null) - { - string iconPath = Path.Combine(programFilesFolder - ?? throw new InvalidOperationException("The ProgramFiles environment variable is not set."), "pCloud Drive", "pCloud.exe"); - var iconFile = Win32Helper.ExtractSelectedIconsFromDLL(iconPath, new List() { 32512 }, 32).FirstOrDefault(); - - App.AppModel.PCloudDrivePath = syncedFolder; - - results.Add(new CloudProvider(CloudProviders.pCloud) - { - Name = $"pCloud Drive", - SyncFolder = syncedFolder, - IconData = iconFile?.IconData - }); - } - - return Task.FromResult>(results); - } - - private static Task> DetectNutstoreDrive() - { - var results = new List(); - using var NutstoreKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Nutstore"); - - if (NutstoreKey is not null) - { - string iconPath = Path.Combine(programFilesFolder - ?? throw new InvalidOperationException("The ProgramFiles environment variable is not set."), "Nutstore", "Nutstore.exe"); - var iconFile = Win32Helper.ExtractSelectedIconsFromDLL(iconPath, new List() { 101 }).FirstOrDefault(); - - using var syncRootMangerKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SyncRootManager"); - if (syncRootMangerKey is not null) - { - var syncRootIds = syncRootMangerKey.GetSubKeyNames(); - foreach (var syncRootId in syncRootIds) - { - if (!syncRootId.StartsWith("Nutstore-")) continue; - - var sid = syncRootId.Split('!')[1]; - using var syncRootKey = syncRootMangerKey.OpenSubKey($@"{syncRootId}\UserSyncRoots"); - var userSyncRoot = syncRootKey?.GetValue(sid)?.ToString(); - if (string.IsNullOrEmpty(userSyncRoot)) continue; - - results.Add(new CloudProvider(CloudProviders.Nutstore) - { - Name = $"Nutstore", - SyncFolder = userSyncRoot, - IconData = iconFile?.IconData - }); - } - } - } - - return Task.FromResult>(results); - } - - private static Task> DetectSeadriveDrive() - { - var results = new List(); - using var SeadriveKey = Registry.CurrentUser.OpenSubKey(@"Software\SeaDrive\Seafile Drive Client\Settings"); - - var syncFolder = (string?)SeadriveKey?.GetValue("seadriveRoot"); - if (SeadriveKey is not null) - { - string iconPath = Path.Combine(programFilesFolder - ?? throw new InvalidOperationException("The ProgramFiles environment variable is not set."), "SeaDrive", "bin", "seadrive.exe"); - var iconFile = Win32Helper.ExtractSelectedIconsFromDLL(iconPath, new List() { 101 }).FirstOrDefault(); - - results.Add(new CloudProvider(CloudProviders.Seadrive) - { - Name = $"Seadrive", - SyncFolder = syncFolder, - IconData = iconFile?.IconData - }); - } - - return Task.FromResult>(results); - } - - private static Task> DetectAutodeskDrive() - { - var results = new List(); - using var AutodeskKey = Registry.LocalMachine.OpenSubKey(@"Software\Autodesk\Desktop Connector"); - - if (AutodeskKey is not null) - { - string iconPath = Path.Combine(programFilesFolder - ?? throw new InvalidOperationException("The ProgramFiles environment variable is not set."), "Autodesk", "Desktop Connector", "DesktopConnector.Applications.Tray.exe"); - var iconFile = Win32Helper.ExtractSelectedIconsFromDLL(iconPath, new List() { 32512 }).FirstOrDefault(); - var mainFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "DC"); - var autodeskFolders = Directory.GetDirectories(mainFolder, "", SearchOption.AllDirectories); - - foreach (var autodeskFolder in autodeskFolders) - { - var folderName = Path.GetFileName(autodeskFolder); - if (folderName is not null) - results.Add(new CloudProvider(CloudProviders.Autodesk) - { - Name = $"Autodesk - {Path.GetFileName(autodeskFolder)}", - SyncFolder = autodeskFolder, - IconData = iconFile?.IconData - }); - } - } - - return Task.FromResult>(results); - } - - private static string GetDriveType(string driveIdentifier, RegistryKey? namespaceSubKey, RegistryKey? syncRootManagerKey) - { - // Drive specific - if (driveIdentifier.StartsWith("iCloudDrive")) - return "iCloudDrive"; - if (driveIdentifier.StartsWith("iCloudPhotos")) - return "iCloudPhotos"; - if (driveIdentifier.StartsWith("ownCloud")) - return "ownCloud"; - if (driveIdentifier.StartsWith("ProtonDrive")) - return "ProtonDrive"; - if (driveIdentifier.StartsWith("SyncCom")) - return "SyncCom"; - - // Nextcloud specific - var appNameFromNamespace = (string?)namespaceSubKey?.GetValue("ApplicationName"); - if (!string.IsNullOrEmpty(appNameFromNamespace) && appNameFromNamespace == "Nextcloud") - return appNameFromNamespace; - - // kDrive specific - var appNameFromSyncRoot = (string?)syncRootManagerKey?.OpenSubKey(driveIdentifier)?.GetValue(string.Empty); - if (!string.IsNullOrEmpty(appNameFromNamespace) && appNameFromNamespace == "kDrive") - return appNameFromNamespace; - if (!string.IsNullOrEmpty(appNameFromSyncRoot) && appNameFromSyncRoot == "kDrive") - return appNameFromSyncRoot; - - return driveIdentifier; - } - } -} diff --git a/src/Files.App/Utils/Cloud/Detector/CloudDetector.cs b/src/Files.App/Utils/Cloud/Detector/CloudDetector.cs index 350dead580f1..405bd8a89361 100644 --- a/src/Files.App/Utils/Cloud/Detector/CloudDetector.cs +++ b/src/Files.App/Utils/Cloud/Detector/CloudDetector.cs @@ -44,14 +44,7 @@ private static IEnumerable EnumerateDetectors() yield return new GoogleDriveCloudDetector(); yield return new DropBoxCloudDetector(); yield return new BoxCloudDetector(); -#if WINDOWS - // Registry and executable icon based - yield return new GenericCloudDetector(); -#endif yield return new SynologyDriveCloudDetector(); -#if WINDOWS - yield return new OXDriveCloudDetector(); -#endif } } } diff --git a/src/Files.App/Utils/Cloud/Detector/GenericCloudDetector.Windows.cs b/src/Files.App/Utils/Cloud/Detector/GenericCloudDetector.Windows.cs deleted file mode 100644 index b3e2afa9976f..000000000000 --- a/src/Files.App/Utils/Cloud/Detector/GenericCloudDetector.Windows.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Utils.Cloud -{ - /// - /// Provides an utility for generic cloud detection. - /// - public sealed class GenericCloudDetector : AbstractCloudDetector - { - protected override async IAsyncEnumerable GetProviders() - { - foreach (var provider in await CloudDrivesDetector.DetectCloudDrives()) - { - yield return provider; - } - } - } -} diff --git a/src/Files.App/Utils/Cloud/Detector/OXDriveCloudDetector.Windows.cs b/src/Files.App/Utils/Cloud/Detector/OXDriveCloudDetector.Windows.cs deleted file mode 100644 index c5e7e43af040..000000000000 --- a/src/Files.App/Utils/Cloud/Detector/OXDriveCloudDetector.Windows.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Microsoft.Win32; -using System.IO; -using Windows.Storage; - -namespace Files.App.Utils.Cloud -{ - /// - /// Provides an utility for OX Drive Cloud detection. - /// - public sealed class OXDriveCloudDetector : AbstractCloudDetector - { - protected override async IAsyncEnumerable GetProviders() - { - var syncFolder = await GetOXDriveSyncFolder(); - if (!string.IsNullOrEmpty(syncFolder)) - { - var iconFile = GetOXDriveIconFile(); - yield return new CloudProvider(CloudProviders.OXDrive) - { - Name = "OX Drive", - SyncFolder = syncFolder, - IconData = iconFile?.IconData - }; - } - } - public static async Task GetOXDriveSyncFolder() - { - var jsonPath = Path.Combine(UserDataPaths.GetDefault().LocalAppData, "Open-Xchange", "OXDrive", "userConfig.json"); - if (!File.Exists(jsonPath)) - return null; - - var configFile = await StorageFile.GetFileFromPathAsync(jsonPath); - using var jsonDoc = JsonDocument.Parse(await FileIO.ReadTextAsync(configFile)); - var jsonElem = jsonDoc.RootElement; - - string? syncFolderPath = null; - - if (jsonElem.TryGetProperty("Accounts", out var accounts) && accounts.GetArrayLength() > 0) - { - var account = accounts[0]; - - if (account.TryGetProperty("MainFolderPath", out var folderPathElem)) - syncFolderPath = folderPathElem.GetString(); - } - - return syncFolderPath; - } - - private static IconFileInfo? GetOXDriveIconFile() - { - var installPath = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Open-Xchange\OXDrive", "InstallDir", null) as string; - - // Fallback to default known path if not found in the registry. - if (string.IsNullOrEmpty(installPath)) - { - var pfX86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); - if (string.IsNullOrEmpty(pfX86)) - return null; - - installPath = Path.Combine(pfX86, "Open-Xchange", "OXDrive"); - } - - var oxDriveFilePath = Path.Combine(installPath, "OXDrive.exe"); - if (!File.Exists(oxDriveFilePath)) - { - return null; - } - - // Extract the icon from the OXDrive executable (though it is executable, it contains icons) - var icons = Win32Helper.ExtractSelectedIconsFromDLL(oxDriveFilePath, new List { 0 }, 32); - return icons.FirstOrDefault(); - } - } -} diff --git a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs index 21e7a87b7a35..38d7d38a07af 100644 --- a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -191,4 +190,3 @@ private void Save(Dictionary entries) } } } -#endif diff --git a/src/Files.App/Utils/FileTags/FileTagsDatabase.cs b/src/Files.App/Utils/FileTags/FileTagsDatabase.cs index ee0e788f3cbc..853c5bb1f9b9 100644 --- a/src/Files.App/Utils/FileTags/FileTagsDatabase.cs +++ b/src/Files.App/Utils/FileTags/FileTagsDatabase.cs @@ -1,263 +1,11 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if WINDOWS -using Microsoft.Win32; -using System.Runtime.CompilerServices; -using System.Security; -using Windows.ApplicationModel; -using static Files.App.Helpers.RegistryHelpers; -using static Files.App.Utils.FileTags.TaggedFileRegistry; -#endif using JsonSerializer = System.Text.Json.JsonSerializer; namespace Files.App.Utils.FileTags { public sealed partial class FileTagsDatabase { -#if WINDOWS - private static string? _FileTagsKey; - private string? FileTagsKey => _FileTagsKey ??= SafetyExtensions.IgnoreExceptions(() => @$"Software\Files Community\{Package.Current.Id.Name}\v1\FileTags"); - - public void SetTags(string filePath, ulong? frn, string[] tags) - { - if (FileTagsKey is null) - return; - - if (tags is []) - { - using var existingFilePathKey = Registry.CurrentUser.OpenSubKey(CombineKeys(FileTagsKey, filePath), writable: true); - if (existingFilePathKey is not null) - SaveValues(existingFilePathKey, null); - - if (frn is not null) - { - using var existingFrnKey = Registry.CurrentUser.OpenSubKey(CombineKeys(FileTagsKey, "FRN", frn.Value.ToString()), writable: true); - if (existingFrnKey is not null) - SaveValues(existingFrnKey, null); - } - - return; - } - - using var filePathKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, filePath)); - - var newTag = new TaggedFile() - { - FilePath = filePath, - Frn = frn, - Tags = tags - }; - SaveValues(filePathKey, newTag); - - if (frn is not null) - { - using var frnKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, "FRN", frn.Value.ToString())); - SaveValues(frnKey, newTag); - } - } - - private TaggedFile? FindTag(string? filePath, ulong? frn) - { - if (FileTagsKey is null) - return null; - - if (filePath is not null) - { - using var filePathKey = Registry.CurrentUser.OpenSubKey(CombineKeys(FileTagsKey, filePath), writable: true); - if (filePathKey is not null && filePathKey.ValueCount > 0) - { - var tag = new TaggedFile(); - BindValues(filePathKey, tag); - if (frn is not null) - { - // Keep entry updated - tag.Frn = frn; - var value = frn.Value; - filePathKey.SetValue(nameof(TaggedFile.Frn), Unsafe.As(ref value), RegistryValueKind.QWord); - } - return tag; - } - } - - if (frn is not null) - { - using var frnKey = Registry.CurrentUser.OpenSubKey(CombineKeys(FileTagsKey, "FRN", frn.Value.ToString()), writable: true); - if (frnKey is not null && frnKey.ValueCount > 0) - { - var tag = new TaggedFile(); - BindValues(frnKey, tag); - if (filePath is not null) - { - // Keep entry updated - tag.FilePath = filePath; - frnKey.SetValue(nameof(TaggedFile.FilePath), filePath, RegistryValueKind.String); - } - return tag; - } - } - - return null; - } - - public void UpdateTag(string oldFilePath, ulong? frn, string? newFilePath) - { - if (FileTagsKey is null) - return; - - var tag = FindTag(oldFilePath, null); - using var filePathKey = Registry.CurrentUser.OpenSubKey(CombineKeys(FileTagsKey, oldFilePath), writable: true); - if (filePathKey is not null) - SaveValues(filePathKey, null); - - if (tag is not null) - { - tag.Frn = frn ?? tag.Frn; - tag.FilePath = newFilePath ?? tag.FilePath; - - if (frn is not null) - { - using var newFrnKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, "FRN", frn.Value.ToString())); - SaveValues(newFrnKey, tag); - } - - if (newFilePath is not null) - { - using var newFilePathKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, newFilePath)); - SaveValues(newFilePathKey, tag); - } - } - } - - public void UpdateTag(ulong oldFrn, ulong? frn, string? newFilePath) - { - if (FileTagsKey is null) - return; - - var tag = FindTag(null, oldFrn); - using var frnKey = Registry.CurrentUser.OpenSubKey(CombineKeys(FileTagsKey, "FRN", oldFrn.ToString()), writable: true); - if (frnKey is not null) - SaveValues(frnKey, null); - - if (tag is not null) - { - tag.Frn = frn ?? tag.Frn; - tag.FilePath = newFilePath ?? tag.FilePath; - - if (frn is not null) - { - using var newFrnKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, "FRN", frn.Value.ToString())); - SaveValues(newFrnKey, tag); - } - - if (newFilePath is not null) - { - using var newFilePathKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, newFilePath)); - SaveValues(newFilePathKey, tag); - } - } - } - - public string[] GetTags(string? filePath, ulong? frn) - { - return FindTag(filePath, frn)?.Tags ?? []; - } - - public IEnumerable GetAll() - { - var list = new List(); - - if (FileTagsKey is not null) - { - try - { - IterateKeys(list, FileTagsKey, 0); - } - catch (SecurityException) - { - // Handle edge case where IterateKeys results in SecurityException - } - } - - return list; - } - - public IEnumerable GetAllUnderPath(string folderPath) - { - folderPath = folderPath.Replace('/', '\\').TrimStart('\\'); - var list = new List(); - - if (FileTagsKey is not null) - { - try - { - IterateKeys(list, CombineKeys(FileTagsKey, folderPath), 0); - } - catch (SecurityException) - { - // Handle edge case where IterateKeys results in SecurityException - } - } - - return list; - } - - public void Import(string json) - { - if (FileTagsKey is null) - return; - - var tags = JsonSerializer.Deserialize(json, AppJsonSerializerContext.Default.TaggedFileArray); - - Registry.CurrentUser.DeleteSubKeyTree(FileTagsKey, false); - if (tags is null) - { - return; - } - foreach (var tag in tags) - { - using var filePathKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, tag.FilePath)); - SaveValues(filePathKey, tag); - if (tag.Frn is not null) - { - using var frnKey = Registry.CurrentUser.CreateSubKey(CombineKeys(FileTagsKey, "FRN", tag.Frn.Value.ToString())); - SaveValues(frnKey, tag); - } - } - } - - public string Export() - { - var list = new List(); - - if (FileTagsKey is not null) - IterateKeys(list, FileTagsKey, 0); - - return JsonSerializer.Serialize(list, AppJsonSerializerContext.Default.ListTaggedFile); - } - - private void IterateKeys(List list, string path, int depth) - { - using var key = Registry.CurrentUser.OpenSubKey(path); - if (key is null) - return; - - if (key.ValueCount > 0) - { - var tag = new TaggedFile(); - BindValues(key, tag); - list.Add(tag); - } - - foreach (var subKey in key.GetSubKeyNames()) - { - // Skip FRN key - if (depth == 0 && subKey == "FRN") - continue; - - IterateKeys(list, CombineKeys(path, subKey), depth + 1); - } - } -#endif } } diff --git a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs index 5241acaba143..b25f6caf6056 100644 --- a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Tags; using Microsoft.Extensions.Logging; using System; @@ -183,4 +182,3 @@ public static void UpdateTagsDb() public static ulong? GetFileFRN(string filePath) => null; } } -#endif diff --git a/src/Files.App/Utils/FileTags/FileTagsHelper.cs b/src/Files.App/Utils/FileTags/FileTagsHelper.cs index ab1a1f28c870..78941f201675 100644 --- a/src/Files.App/Utils/FileTags/FileTagsHelper.cs +++ b/src/Files.App/Utils/FileTags/FileTagsHelper.cs @@ -6,9 +6,6 @@ using Windows.Foundation.Metadata; using Windows.Storage; using Windows.Storage.FileProperties; -#if WINDOWS -using Windows.Win32; -#endif using IO = System.IO; namespace Files.App.Utils.FileTags @@ -20,120 +17,6 @@ public static partial class FileTagsHelper public static FileTagsDatabase GetDbInstance() => dbInstance.Value; -#if WINDOWS - public static string[] ReadFileTag(string filePath) - { - var tagString = Win32Helper.ReadStringFromFile($"{filePath}:files"); - return tagString?.Split(',', StringSplitOptions.RemoveEmptyEntries) ?? []; - } - - public static async Task WriteFileTagAsync(string filePath, string[] tag, CancellationToken cancellationToken = default) - { - var isDateOk = false; - var isReadOnly = false; - System.Runtime.InteropServices.ComTypes.FILETIME dateModified = default; - - try - { - cancellationToken.ThrowIfCancellationRequested(); - isDateOk = Win32Helper.GetFileDateModified(filePath, out dateModified); // Backup date modified - isReadOnly = Win32Helper.HasFileAttribute(filePath, IO.FileAttributes.ReadOnly); - if (isReadOnly) // Unset read-only attribute (#7534) - Win32Helper.UnsetFileAttribute(filePath, IO.FileAttributes.ReadOnly); - - var currentTags = ReadFileTag(filePath); - if (tag.SequenceEqual(currentTags)) - return true; - - bool succeeded = tag.Length == 0 - ? PInvoke.DeleteFileFromApp($"{filePath}:files") - : Win32Helper.WriteStringToFile($"{filePath}:files", string.Join(',', tag)); - if (!succeeded) - { - await SafetyExtensions.IgnoreExceptions(() => MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => - { - ContentDialog dialog = new() - { - Title = Strings.ErrorApplyingTagTitle.GetLocalizedResource(), - Content = Strings.ErrorApplyingTagContent.GetLocalizedResource(), - PrimaryButtonText = "Ok".GetLocalizedResource() - }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - dialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - await dialog.TryShowAsync(); - }), App.Logger); - } - - return succeeded; - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - return false; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Failed to write tags for '{FilePath}'.", LogPathHelper.RedactPath(filePath)); - return false; - } - finally - { - if (isReadOnly) // Restore read-only attribute (#7534) - SafetyExtensions.IgnoreExceptions(() => Win32Helper.SetFileAttribute(filePath, IO.FileAttributes.ReadOnly), App.Logger); - if (isDateOk) - SafetyExtensions.IgnoreExceptions(() => Win32Helper.SetFileDateModified(filePath, dateModified), App.Logger); // Restore date modified - } - } - - public static void UpdateTagsDb() - { - // File reference numbers are NTFS-only - if (!OperatingSystem.IsWindows()) - return; - - var dbInstance = GetDbInstance(); - foreach (var file in dbInstance.GetAll()) - { - var pathFromFrn = Win32Helper.PathFromFileId(file.Frn ?? 0, file.FilePath); - if (pathFromFrn is not null) - { - // Frn is valid, update file path - var tag = ReadFileTag(pathFromFrn.Replace(@"\\?\", "", StringComparison.Ordinal)); - if (tag is not null && tag.Any()) - { - dbInstance.UpdateTag(file.Frn ?? 0, null, pathFromFrn.Replace(@"\\?\", "", StringComparison.Ordinal)); - dbInstance.SetTags(pathFromFrn.Replace(@"\\?\", "", StringComparison.Ordinal), file.Frn, tag); - } - else - { - dbInstance.SetTags(pathFromFrn.Replace(@"\\?\", "", StringComparison.Ordinal), file.Frn, []); - } - } - else - { - var tag = ReadFileTag(file.FilePath); - if (tag is not null && tag.Any()) - { - if (!SafetyExtensions.IgnoreExceptions(() => - { - var frn = GetFileFRN(file.FilePath); - dbInstance.UpdateTag(file.FilePath, frn, null); - dbInstance.SetTags(file.FilePath, frn, tag); - }, App.Logger)) - { - dbInstance.SetTags(file.FilePath, null, []); - } - } - else - { - dbInstance.SetTags(file.FilePath, null, []); - } - } - } - } - -#endif /// /// Prompts the user for confirmation, then removes all tags from the given items that have tags. @@ -159,29 +42,8 @@ public static async Task RemoveTagsAsync(IEnumerable items) return true; } -#if WINDOWS - public static ulong? GetFileFRN(string filePath) => Win32Helper.GetFileFRN(filePath); -#endif -#if WINDOWS - public static Task GetFileFRN(IStorageItem? item) - { - return item switch - { - BaseStorageFolder { Properties: not null } folder => GetFileFRN(folder.Properties), - BaseStorageFile { Properties: not null } file => GetFileFRN(file.Properties), - _ => Task.FromResult(null), - }; - - static async Task GetFileFRN(IStorageItemExtraProperties properties) - { - var extra = await properties.RetrievePropertiesAsync((string[])["System.FileFRN"]); - return (ulong?)extra["System.FileFRN"]; - } - } -#else // File reference numbers do not exist on Linux; tags are keyed by path. public static Task GetFileFRN(IStorageItem? item) => Task.FromResult(null); -#endif } } diff --git a/src/Files.App/Utils/Global/WindowsStorageDeviceWatcher.cs b/src/Files.App/Utils/Global/WindowsStorageDeviceWatcher.cs deleted file mode 100644 index de9f3cda9e24..000000000000 --- a/src/Files.App/Utils/Global/WindowsStorageDeviceWatcher.cs +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.IO; -using System.Runtime.InteropServices; -using Windows.Devices.Enumeration; -using Windows.Devices.Portable; -using Windows.Storage; - -namespace Files.App.Utils -{ - public sealed class WindowsStorageDeviceWatcher : IStorageDeviceWatcher - { - public event EventHandler? DeviceAdded; - public event EventHandler? DeviceRemoved; - public event EventHandler? EnumerationCompleted; - public event EventHandler? DeviceModified; - - private DeviceWatcher watcher; - - public bool CanBeStarted => watcher.Status is DeviceWatcherStatus.Created or DeviceWatcherStatus.Stopped or DeviceWatcherStatus.Aborted; - - public WindowsStorageDeviceWatcher() - { - watcher = DeviceInformation.CreateWatcher(StorageDevice.GetDeviceSelector()); - watcher.Added += Watcher_Added; - watcher.Removed += Watcher_Removed; - watcher.EnumerationCompleted += Watcher_EnumerationCompleted; - - SetupWin32Watcher(); - } - - private void SetupWin32Watcher() - { - WindowsDriveManager.Default.DeviceAdded += Win32_OnDeviceAdded; - WindowsDriveManager.Default.DeviceRemoved += Win32_OnDeviceRemoved; - WindowsDriveManager.Default.DeviceInserted += Win32_OnDeviceEjectedOrInserted; - WindowsDriveManager.Default.DeviceEjected += Win32_OnDeviceEjectedOrInserted; - } - - private void Win32_OnDeviceEjectedOrInserted(object? sender, DeviceEventArgs e) - { - DeviceModified?.Invoke(this, e.DeviceId); - } - - private void Win32_OnDeviceRemoved(object? sender, DeviceEventArgs e) - { - DeviceRemoved?.Invoke(this, e.DeviceId); - } - - private async void Win32_OnDeviceAdded(object? sender, DeviceEventArgs e) - { - var driveAdded = new DriveInfo(e.DeviceId); - if (!driveAdded.IsReady && !IsUnauthorizedDrive(driveAdded)) - return; - - var rootResult = await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(e.DeviceId).AsTask()); - if (rootResult.Result is not { } rootAdded) - { - App.Logger.LogWarning($"{rootResult.ErrorCode}: Attempting to add the device, {e.DeviceId}," - + " failed at the StorageFolder initialization step. This device will be ignored."); - return; - } - - var type = DriveHelpers.GetDriveType(driveAdded); - var label = DriveHelpers.GetExtendedDriveLabel(driveAdded); - DriveItem driveItem = await DriveItem.CreateFromPropertiesAsync(rootAdded, e.DeviceId, label, type); - - DeviceAdded?.Invoke(this, driveItem); - } - - private void Watcher_EnumerationCompleted(DeviceWatcher sender, object args) - { - EnumerationCompleted?.Invoke(this, EventArgs.Empty); - } - - private void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) - { - DeviceRemoved?.Invoke(this, args.Id); - } - - private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args) - { - string deviceId = args.Id; - StorageFolder root; - try - { - root = StorageDevice.FromId(deviceId); - } - catch (Exception ex) when (ex is ArgumentException or UnauthorizedAccessException or COMException) - { - App.Logger.LogWarning($"{ex.GetType()}: Attempting to add the device, {LogPathHelper.RedactPath(args.Name)}," - + $" failed at the StorageFolder initialization step. This device will be ignored. Device ID: {deviceId}"); - return; - } - - Data.Items.DriveType type; - string label; - try - { - // Check if this drive is associated with a drive letter - var driveAdded = new DriveInfo(root.Path); - if (!driveAdded.IsReady && !IsUnauthorizedDrive(driveAdded)) - return; - - type = DriveHelpers.GetDriveType(driveAdded); - label = DriveHelpers.GetExtendedDriveLabel(driveAdded); - } - catch (ArgumentException) - { - type = Data.Items.DriveType.Removable; - label = string.Empty; - } - - var driveItem = await DriveItem.CreateFromPropertiesAsync(root, deviceId, label, type); - - DeviceAdded?.Invoke(this, driveItem); - } - - public void Start() - { - WindowsDriveManager.Default.Start(); - watcher.Start(); - } - - public void Stop() - { - if (watcher.Status is DeviceWatcherStatus.Started or DeviceWatcherStatus.EnumerationCompleted) - { - watcher.Stop(); - } - - watcher.Added -= Watcher_Added; - watcher.Removed -= Watcher_Removed; - watcher.EnumerationCompleted -= Watcher_EnumerationCompleted; - - WindowsDriveManager.Default.DeviceAdded -= Win32_OnDeviceAdded; - WindowsDriveManager.Default.DeviceRemoved -= Win32_OnDeviceRemoved; - WindowsDriveManager.Default.DeviceInserted -= Win32_OnDeviceEjectedOrInserted; - WindowsDriveManager.Default.DeviceEjected -= Win32_OnDeviceEjectedOrInserted; - WindowsDriveManager.Default.Stop(); - } - - private bool IsUnauthorizedDrive(DriveInfo driveInfo) - { - try - { - _ = Directory.EnumerateFileSystemEntries(driveInfo.Name).FirstOrDefault(); - return false; - } - catch (UnauthorizedAccessException) - { - // probably BitLocker locked drive. - return true; - } - catch (IOException ex) when (ex.HResult == unchecked((int)0x80310000)) // FVE_E_LOCKED_VOLUME - { - // BitLocker locked drive. - return true; - } - catch - { - return false; - } - } - } -} diff --git a/src/Files.App/Utils/Library/LibraryManager.Windows.cs b/src/Files.App/Utils/Library/LibraryManager.Windows.cs deleted file mode 100644 index e6cff439c3e0..000000000000 --- a/src/Files.App/Utils/Library/LibraryManager.Windows.cs +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Dialogs; -using Microsoft.Extensions.Logging; -using Microsoft.UI.Xaml.Controls; -using System.Collections.Specialized; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using Windows.System; -using Windows.Win32; -using Windows.Win32.UI.Shell; -using Visibility = Microsoft.UI.Xaml.Visibility; - -namespace Files.App.Utils.Library -{ - public sealed partial class LibraryManager : IDisposable - { - private void InitializeWatcher() - { - if (librariesWatcher is not null) - return; - - librariesWatcher = new FileSystemWatcher - { - Path = ShellLibraryItem.LibrariesPath, - Filter = "*" + ShellLibraryItem.EXTENSION, - NotifyFilter = NotifyFilters.Attributes | NotifyFilters.LastWrite | NotifyFilters.FileName, - IncludeSubdirectories = false, - }; - - librariesWatcher.Created += OnLibraryChanged; - librariesWatcher.Changed += OnLibraryChanged; - librariesWatcher.Deleted += OnLibraryChanged; - librariesWatcher.Renamed += OnLibraryRenamed; - - librariesWatcher.EnableRaisingEvents = true; - } - - public static async Task> ListUserLibraries() - { - var libraries = await STATask.Run(() => - { - try - { - var libraryItems = new List(); - // https://learn.microsoft.com/windows/win32/search/-search-win7-development-scenarios#library-descriptions - var libFiles = Directory.EnumerateFiles(ShellLibraryItem.LibrariesPath, "*" + ShellLibraryItem.EXTENSION); - foreach (var libFile in libFiles) - { - using var libraryFile = ShellItem.Open(libFile); - using var library = new ShellLibraryEx(libraryFile.IShellItem, true); - libraryItems.Add(ShellFolderExtensions.GetShellLibraryItem(library, libFile)); - } - return libraryItems; - } - catch (Exception e) - { - App.Logger.LogWarning(e, null); - } - - return []; - }, App.Logger); - - return libraries.Select(lib => new LibraryLocationItem(lib)).ToList(); - } - - public async Task CreateNewLibrary(string name) - { - if (string.IsNullOrWhiteSpace(name) || !CanCreateLibrary(name).result) - return false; - - var shellLibrary = await STATask.Run(() => - { - try - { - using var library = new ShellLibraryEx(name, PInvoke.FOLDERID_Libraries, false); - library.Folders.Add(ShellItem.Open(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))); // Add default folder so it's not empty - library.Commit(); - library.Reload(); - var libraryPath = library.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING); - return Task.FromResult(libraryPath is null - ? null - : ShellFolderExtensions.GetShellLibraryItem(library, libraryPath)); - } - catch (Exception e) - { - App.Logger.LogWarning(e, null); - } - - return Task.FromResult(null); - }, App.Logger); - - if (shellLibrary is null) - return false; - - var newLib = new LibraryLocationItem(shellLibrary); - lock (libraries) - { - libraries.Add(newLib); - } - DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newLib)); - return true; - } - - public async Task UpdateLibrary(string libraryPath, string? defaultSaveFolder = null, string[]? folders = null, bool? isPinned = null) - { - if (string.IsNullOrWhiteSpace(libraryPath) || (defaultSaveFolder is null && folders is null && isPinned is null)) - // Nothing to update - return null; - - var item = await STATask.Run(() => - { - try - { - bool updated = false; - using var libraryFile = ShellItem.Open(libraryPath); - using var library = new ShellLibraryEx(libraryFile.IShellItem, false); - if (folders is not null) - { - if (folders.Length > 0) - { - var foldersToRemove = library.Folders - .Where(f => !folders.Any(folderPath => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase))) - .ToList(); - foreach (var toRemove in foldersToRemove) - { - if (library.Folders.Remove(toRemove)) - { - toRemove.Dispose(); - updated = true; - } - } - var foldersToAdd = folders.Distinct(StringComparer.OrdinalIgnoreCase) - .Where(folderPath => !library.Folders.Any(f => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase))) - .Select(ShellItem.Open) - .ToList(); - foreach (var toAdd in foldersToAdd) - { - library.Folders.Add(toAdd); - updated = true; - } - foreach (var toAdd in foldersToAdd) - { - toAdd.Dispose(); - } - } - } - if (defaultSaveFolder is not null) - { - using var saveFolder = ShellItem.Open(defaultSaveFolder); - library.DefaultSaveFolder = saveFolder; - updated = true; - } - if (isPinned is not null) - { - library.PinnedToNavigationPane = isPinned == true; - updated = true; - } - if (updated) - { - library.Commit(); - library.Reload(); // Reload folders list - return Task.FromResult(ShellFolderExtensions.GetShellLibraryItem(library, libraryPath)); - } - } - catch (Exception e) - { - App.Logger.LogWarning(e, null); - } - - return Task.FromResult(null); - }, App.Logger); - - var newLib = item is not null ? new LibraryLocationItem(item) : null; - if (newLib is not null) - { - var libItem = Libraries.FirstOrDefault(l => string.Equals(l.Path, libraryPath, StringComparison.OrdinalIgnoreCase)); - if (libItem is not null) - { - lock (libraries) - { - libraries[libraries.IndexOf(libItem)] = newLib; - } - DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, newLib, libItem)); - } - return newLib; - } - return null; - } - - public static async Task ShowRestoreDefaultLibrariesDialogAsync() - { - var dialog = new DynamicDialog(new DynamicDialogViewModel - { - TitleText = Strings.DialogRestoreLibrariesTitleText.GetLocalizedResource(), - SubtitleText = Strings.DialogRestoreLibrariesSubtitleText.GetLocalizedResource(), - PrimaryButtonText = Strings.Restore.GetLocalizedResource(), - CloseButtonText = Strings.Cancel.GetLocalizedResource(), - PrimaryButtonAction = async (vm, e) => - { - await ContextMenu.InvokeVerb("restorelibraries", ShellLibraryItem.LibrariesPath); - await App.LibraryManager.UpdateLibrariesAsync(); - }, - CloseButtonAction = (vm, e) => vm.Hide(), - KeyDownAction = (vm, e) => - { - if (e.Key == VirtualKey.Escape) - { - vm.Hide(); - } - }, - DynamicButtons = DynamicDialogButtons.Primary | DynamicDialogButtons.Cancel - }); - await dialog.ShowAsync(); - } - - public static async Task ShowCreateNewLibraryDialogAsync() - { - var inputText = new TextBox - { - PlaceholderText = Strings.FolderWidgetCreateNewLibraryInputPlaceholderText.GetLocalizedResource() - }; - var tipText = new TextBlock - { - Text = string.Empty, - Visibility = Visibility.Collapsed - }; - - var dialog = new DynamicDialog(new DynamicDialogViewModel - { - DisplayControl = new Grid - { - Children = - { - new StackPanel - { - Spacing = 4d, - Children = - { - inputText, - tipText - } - } - } - }, - TitleText = Strings.FolderWidgetCreateNewLibraryDialogTitleText.GetLocalizedResource(), - SubtitleText = Strings.SideBarCreateNewLibraryText.GetLocalizedResource(), - PrimaryButtonText = Strings.Create.GetLocalizedResource(), - CloseButtonText = Strings.Cancel.GetLocalizedResource(), - PrimaryButtonAction = async (vm, e) => - { - var (result, reason) = App.LibraryManager.CanCreateLibrary(inputText.Text); - tipText.Text = reason; - tipText.Visibility = result ? Visibility.Collapsed : Visibility.Visible; - if (!result) - { - e.Cancel = true; - return; - } - await App.LibraryManager.CreateNewLibrary(inputText.Text); - }, - CloseButtonAction = (vm, e) => - { - vm.Hide(); - }, - KeyDownAction = async (vm, e) => - { - if (e.Key == VirtualKey.Enter) - { - await App.LibraryManager.CreateNewLibrary(inputText.Text); - } - else if (e.Key == VirtualKey.Escape) - { - vm.Hide(); - } - }, - DynamicButtons = DynamicDialogButtons.Primary | DynamicDialogButtons.Cancel - }); - await dialog.ShowAsync(); - } - - private void OnLibraryChanged(WatcherChangeTypes changeType, string? oldPath, string? newPath) - { - if (newPath is not null && (!newPath.ToLowerInvariant().EndsWith(ShellLibraryItem.EXTENSION, StringComparison.Ordinal) || !File.Exists(newPath))) - { - System.Diagnostics.Debug.WriteLine($"Ignored library event: {changeType}, {oldPath} -> {newPath}"); - return; - } - - System.Diagnostics.Debug.WriteLine($"Library event: {changeType}, {oldPath} -> {newPath}"); - - if (!changeType.HasFlag(WatcherChangeTypes.Deleted)) - { - if (newPath is null) - { - App.Logger.LogWarning($"Failed to open library after {changeType}: {LogPathHelper.RedactPath(newPath)}"); - return; - } - - using var libraryFile = SafetyExtensions.IgnoreExceptions(() => ShellItem.Open(newPath)); - var library = SafetyExtensions.IgnoreExceptions(() => new ShellLibraryEx(libraryFile!.IShellItem, true)); - if (library is null) - { - App.Logger.LogWarning($"Failed to open library after {changeType}: {LogPathHelper.RedactPath(newPath)}"); - return; - } - - var library1 = SafetyExtensions.IgnoreExceptions(() => ShellFolderExtensions.GetShellLibraryItem(library, newPath)); - if (library1 is null) - { - App.Logger.LogWarning($"Failed to open library after {changeType}: {LogPathHelper.RedactPath(newPath)}"); - return; - } - - string? path = oldPath; - if (string.IsNullOrEmpty(oldPath)) - { - path = library1.FullPath; - } - var changedLibrary = Libraries.FirstOrDefault(l => string.Equals(l.Path, path, StringComparison.OrdinalIgnoreCase)); - if (changedLibrary is not null) - { - lock (libraries) - { - libraries.Remove(changedLibrary); - } - DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, changedLibrary)); - } - // library is null in case it was deleted - if (!Libraries.Any(x => x.Path == library1.FullPath)) - { - var libItem = new LibraryLocationItem(library1); - lock (libraries) - { - libraries.Add(libItem); - } - DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, libItem)); - } - - library.Dispose(); - } - } - - private void OnLibraryChanged(object sender, FileSystemEventArgs e) - { - switch (e.ChangeType) - { - case WatcherChangeTypes.Created: - case WatcherChangeTypes.Changed: - OnLibraryChanged(e.ChangeType, e.FullPath, e.FullPath); - break; - case WatcherChangeTypes.Deleted: - OnLibraryChanged(e.ChangeType, e.FullPath, null); - break; - } - } - - private void OnLibraryRenamed(object sender, RenamedEventArgs e) - => OnLibraryChanged(e.ChangeType, e.OldFullPath, e.FullPath); - - } -} diff --git a/src/Files.App/Utils/Library/LibraryManager.cs b/src/Files.App/Utils/Library/LibraryManager.cs index ddd9bd496c6f..03f6307c21ca 100644 --- a/src/Files.App/Utils/Library/LibraryManager.cs +++ b/src/Files.App/Utils/Library/LibraryManager.cs @@ -36,9 +36,6 @@ public IReadOnlyList Libraries public LibraryManager() { -#if WINDOWS - InitializeWatcher(); -#endif } @@ -46,11 +43,9 @@ public LibraryManager() /// Get libraries of the current user with the help of the FullTrust process. /// /// List of library items -#if !WINDOWS // LINUX-TODO(libraries): shell libraries are unavailable on Linux. public static Task> ListUserLibraries() => Task.FromResult>([]); -#endif public async Task UpdateLibrariesAsync() { @@ -86,10 +81,8 @@ public bool TryGetLibrary(string? path, [NotNullWhen(true)] out LibraryLocationI ///
/// The name of the new library (must be unique) /// The new library if successfully created -#if !WINDOWS public Task CreateNewLibrary(string name) => Task.FromResult(false); -#endif /// /// Update library details. @@ -99,10 +92,8 @@ public Task CreateNewLibrary(string name) /// Update the library folders or null to keep current /// Update the library pinned status or null to keep current /// The new library if successfully updated -#if !WINDOWS public Task UpdateLibrary(string libraryPath, string? defaultSaveFolder = null, string[]? folders = null, bool? isPinned = null) => Task.FromResult(null); -#endif public (bool result, string reason) CanCreateLibrary(string name) { @@ -129,15 +120,11 @@ public Task CreateNewLibrary(string name) return (true, string.Empty); } -#if !WINDOWS public static Task ShowRestoreDefaultLibrariesDialogAsync() => Task.CompletedTask; -#endif -#if !WINDOWS public static Task ShowCreateNewLibraryDialogAsync() => Task.CompletedTask; -#endif diff --git a/src/Files.App/Utils/Serialization/Implementation/DefaultSettingsSerializer.cs b/src/Files.App/Utils/Serialization/Implementation/DefaultSettingsSerializer.cs index b21bb14a3912..ac14968b074a 100644 --- a/src/Files.App/Utils/Serialization/Implementation/DefaultSettingsSerializer.cs +++ b/src/Files.App/Utils/Serialization/Implementation/DefaultSettingsSerializer.cs @@ -2,26 +2,14 @@ // Licensed under the MIT License. using System.IO; -#if WINDOWS -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; -using static Files.App.Helpers.Win32Helper; -using static Files.App.Helpers.Win32PInvoke; -#else using Files.Platform.Linux.Native; -#endif namespace Files.App.Utils.Serialization.Implementation { internal sealed class DefaultSettingsSerializer : ISettingsSerializer { -#if !WINDOWS private static readonly TimeSpan LockTimeout = TimeSpan.FromMilliseconds(250); -#endif private readonly Action? _logWarning; private string? _filePath; @@ -32,7 +20,6 @@ public DefaultSettingsSerializer(Action? logWarning = null) public bool CreateFile(string path) { -#if !WINDOWS try { Directory.CreateDirectory(Path.GetDirectoryName(path)!); @@ -47,20 +34,6 @@ public bool CreateFile(string path) { return false; } -#else - PInvoke.CreateDirectoryFromApp(Path.GetDirectoryName(path), null); - - var hFile = CreateFileFromApp(path, (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_ALWAYS, (uint)File_Attributes.BackupSemantics, IntPtr.Zero); - if (hFile.IsHandleInvalid()) - { - return false; - } - - Win32PInvoke.CloseHandle(hFile); - - _filePath = path; - return true; -#endif } /// @@ -72,7 +45,6 @@ public string ReadFromFile() { ArgumentNullException.ThrowIfNull(_filePath); -#if !WINDOWS try { return File.ReadAllText(_filePath); @@ -81,16 +53,12 @@ public string ReadFromFile() { return string.Empty; } -#else - return ReadStringFromFile(_filePath) ?? string.Empty; -#endif } public bool WithWriteLock(Func writeSettings) { ArgumentNullException.ThrowIfNull(_filePath); -#if !WINDOWS // flock on a private lock file next to the settings file serializes the read/merge/write across windows (processes). // The wait is bounded so a stuck holder cannot freeze the UI; the write itself stays atomic without the lock. using var fileLock = FileLockNative.TryAcquire(_filePath + ".lock", LockTimeout, out var error); @@ -98,38 +66,12 @@ public bool WithWriteLock(Func writeSettings) _logWarning?.Invoke($"Saving settings without the cross-process lock: {error}"); return writeSettings(); -#else - var path = Path.GetFullPath(_filePath).ToUpperInvariant(); - - // Serialize the entire read/merge/write across processes sharing this settings file. - var name = "Files.Settings." + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(path))); - using var mutex = new Mutex(false, name); - try - { - mutex.WaitOne(); - } - catch (AbandonedMutexException) - { - // The previous writer exited; this thread now owns the mutex. - _logWarning?.Invoke("The previous settings writer exited while holding the settings lock."); - } - - try - { - return writeSettings(); - } - finally - { - mutex.ReleaseMutex(); - } -#endif } public bool WriteToFile(string text) { ArgumentNullException.ThrowIfNull(_filePath); -#if !WINDOWS try { // Write to a temp file and rename so a crash never leaves a truncated settings file; @@ -143,9 +85,6 @@ public bool WriteToFile(string text) { return false; } -#else - return WriteStringToFile(_filePath, text); -#endif } } } diff --git a/src/Files.App/Utils/Shell/ContextMenu.cs b/src/Files.App/Utils/Shell/ContextMenu.cs deleted file mode 100644 index a2e06b8eabae..000000000000 --- a/src/Files.App/Utils/Shell/ContextMenu.cs +++ /dev/null @@ -1,393 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Drawing; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using System.Text; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Gdi; -using Windows.Win32.System.Memory; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Utils.Shell -{ - /// - /// Provides a helper for Win32 context menus. - /// - public sealed partial class ContextMenu : Win32ContextMenu, IDisposable - { - private const uint CmicMaskUnicode = 0x00004000; - private static readonly ImageConverter IconConverter = new(); - - private IContextMenu? contextMenu; - private HMENU menu; - private readonly ContextMenuWorkerPool.Worker worker; - private readonly Func? itemFilter; - private readonly Dictionary, Action> loadSubMenuActions = []; - private bool disposedValue; - - private ThreadWithMessageQueue OwningThread => worker.Thread; - - private IContextMenu Menu => contextMenu ?? throw new ObjectDisposedException(nameof(ContextMenu)); - - public List ItemsPath { get; } - - private ContextMenu(IContextMenu contextMenu, HMENU menu, IEnumerable itemsPath, ContextMenuWorkerPool.Worker worker, Func? itemFilter) - { - this.contextMenu = contextMenu; - this.menu = menu; - this.worker = worker; - this.itemFilter = itemFilter; - ItemsPath = itemsPath.ToList(); - Items = []; - } - - public static async Task InvokeVerb(string verb, params string?[] filePaths) - { - using var contextMenu = await GetContextMenuForFiles(filePaths, PInvoke.CMF_DEFAULTONLY); - return contextMenu is not null && await contextMenu.InvokeVerb(verb); - } - - public async Task InvokeVerb(string? verb) - { - if (string.IsNullOrEmpty(verb)) - return false; - - var items = Items ?? throw new InvalidOperationException("The shell context menu has not been initialized."); - var item = items.FirstOrDefault(x => x.CommandString == verb); - if (item is not null && item.ID >= 0) - return await InvokeItem(item.ID); - - try - { - var currentWindows = Win32Helper.GetDesktopWindows(); - HRESULT result = await OwningThread.PostMethod(() => InvokeVerbCore(verb)); - if (result.Failed) - return false; - Win32Helper.BringToForeground(currentWindows); - return true; - } - catch (Exception ex) when (ex is COMException or UnauthorizedAccessException) - { - Debug.WriteLine(ex); - return false; - } - } - - public async Task InvokeItem(int itemId, string? workingDirectory = null) - { - if (itemId < 0) - return false; - - try - { - var currentWindows = Win32Helper.GetDesktopWindows(); - HRESULT result = await OwningThread.PostMethod(() => InvokeItemCore(itemId, workingDirectory)); - if (result.Failed) - return false; - Win32Helper.BringToForeground(currentWindows); - return true; - } - catch (Exception ex) when (ex is COMException or UnauthorizedAccessException) - { - Debug.WriteLine(ex); - return false; - } - } - - private unsafe HRESULT InvokeVerbCore(string verb) - { - byte[] verbBytes = Encoding.ASCII.GetBytes(verb + '\0'); - fixed (byte* verbPointer = verbBytes) - { - CMINVOKECOMMANDINFOEX commandInfo = default; - commandInfo.cbSize = (uint)sizeof(CMINVOKECOMMANDINFOEX); - commandInfo.lpVerb = (PCSTR)verbPointer; - commandInfo.nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL; - return Menu.InvokeCommand((CMINVOKECOMMANDINFO*)&commandInfo); - } - } - - private unsafe HRESULT InvokeItemCore(int itemId, string? workingDirectory) - { - fixed (char* directory = workingDirectory) - { - CMINVOKECOMMANDINFOEX commandInfo = default; - commandInfo.cbSize = (uint)sizeof(CMINVOKECOMMANDINFOEX); - commandInfo.fMask = CmicMaskUnicode; - commandInfo.lpVerb = (PCSTR)(byte*)(nuint)(uint)itemId; - commandInfo.lpVerbW = (PCWSTR)(char*)(nuint)(uint)itemId; - commandInfo.lpDirectoryW = directory; - commandInfo.nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL; - return Menu.InvokeCommand((CMINVOKECOMMANDINFO*)&commandInfo); - } - } - - public static async Task GetContextMenuForFiles(string?[] filePathList, uint flags, Func? itemFilter = null) - { - var worker = ContextMenuWorkerPool.Rent(); - var contextMenu = await worker.Thread.PostMethod(() => - { - var shellItems = new List(); - try - { - foreach (string path in filePathList.WhereNotNull().Where(path => !string.IsNullOrEmpty(path))) - shellItems.Add(ShellFolderExtensions.GetShellItemFromPathOrPIDL(path)); - return Create([.. shellItems], flags, worker, itemFilter); - } - catch - { - return null; - } - finally - { - foreach (ShellItem item in shellItems) - item.Dispose(); - } - }); - - if (contextMenu is null) - ContextMenuWorkerPool.Return(worker); - return contextMenu; - } - - public static async Task GetContextMenuForFiles(ShellItem[] shellItems, uint flags, Func? itemFilter = null) - { - var worker = ContextMenuWorkerPool.Rent(); - var contextMenu = await worker.Thread.PostMethod(() => Create(shellItems, flags, worker, itemFilter)); - if (contextMenu is null) - ContextMenuWorkerPool.Return(worker); - return contextMenu; - } - - private static unsafe ContextMenu? Create(ShellItem[] shellItems, uint flags, ContextMenuWorkerPool.Worker worker, Func? itemFilter) - { - if (shellItems.Length is 0) - return null; - - ITEMIDLIST** pidls = null; - HMENU menu = default; - try - { - pidls = (ITEMIDLIST**)NativeMemory.AllocZeroed((nuint)shellItems.Length, (nuint)sizeof(ITEMIDLIST*)); - for (int index = 0; index < shellItems.Length; index++) - PInvoke.SHGetIDListFromObject(shellItems[index].IShellItem, out pidls[index]).ThrowOnFailure(); - - PInvoke.SHCreateShellItemArrayFromIDLists((uint)shellItems.Length, pidls, out IShellItemArray itemArray).ThrowOnFailure(); - IContextMenu shellContextMenu = BindContextMenu(itemArray); - - menu = PInvoke.CreatePopupMenu(); - shellContextMenu.QueryContextMenu(menu, 0, 1, 0x7FFF, flags).ThrowOnFailure(); - var contextMenu = new ContextMenu(shellContextMenu, menu, shellItems.Select(item => item.ParsingName).WhereNotNull(), worker, itemFilter); - menu = default; - contextMenu.EnumMenuItems(contextMenu.menu, contextMenu.Items!); - return contextMenu; - } - catch (COMException) - { - return null; - } - finally - { - if (!menu.IsNull) - PInvoke.DestroyMenu(menu); - if (pidls is not null) - { - for (int index = 0; index < shellItems.Length; index++) - PInvoke.CoTaskMemFree(pidls[index]); - NativeMemory.Free(pidls); - } - } - } - - private static unsafe IContextMenu BindContextMenu(IShellItemArray itemArray) - { - void* itemArrayPointer = ComInterfaceMarshaller.ConvertToUnmanaged(itemArray); - void* contextMenuPointer = null; - try - { - // Bind through the native vtable so the result can use a uniquely owned generated COM wrapper. - void** vtable = *(void***)itemArrayPointer; - var bindToHandler = - (delegate* unmanaged[MemberFunction])vtable[3]; - Guid handlerId = PInvoke.BHID_SFUIObject; - Guid interfaceId = typeof(IContextMenu).GUID; - HRESULT result = new(bindToHandler(itemArrayPointer, null, &handlerId, &interfaceId, &contextMenuPointer)); - result.ThrowOnFailure(); - return UniqueComInterfaceMarshaller.ConvertToManaged(contextMenuPointer) - ?? throw new InvalidOperationException("The shell did not return a context menu."); - } - finally - { - UniqueComInterfaceMarshaller.Free(contextMenuPointer); - ComInterfaceMarshaller.Free(itemArrayPointer); - } - } - - public static async Task WarmUpQueryContextMenuAsync() - { - using var contextMenu = await GetContextMenuForFiles([$@"{Constants.UserEnvironmentPaths.SystemDrivePath}\"], PInvoke.CMF_NORMAL); - } - - private unsafe void EnumMenuItems(HMENU targetMenu, List result, bool loadSubmenus = false) - { - uint itemCount = unchecked((uint)PInvoke.GetMenuItemCount(targetMenu)); - if (itemCount is unchecked((uint)-1)) - return; - - for (uint index = 0; index < itemCount; index++) - { - const uint bufferLength = 512; - MENUITEMINFOW info = default; - info.cbSize = (uint)sizeof(MENUITEMINFOW); - info.fMask = MENU_ITEM_MASK.MIIM_BITMAP | MENU_ITEM_MASK.MIIM_FTYPE | MENU_ITEM_MASK.MIIM_STRING | MENU_ITEM_MASK.MIIM_ID | MENU_ITEM_MASK.MIIM_SUBMENU; - info.dwTypeData = (char*)NativeMemory.AllocZeroed(bufferLength, sizeof(char)); - info.cch = bufferLength - 1; - - try - { - if (!PInvoke.GetMenuItemInfo(targetMenu, index, true, &info)) - continue; - - var menuItem = new ContextMenuItem { Type = (MENU_ITEM_TYPE)info.fType, ID = (int)(info.wID - 1) }; - if (menuItem.Type == MENU_ITEM_TYPE.MFT_STRING) - { - menuItem.Label = info.dwTypeData.ToString(); - menuItem.CommandString = GetCommandString(Menu, info.wID - 1); - if (itemFilter is not null && (itemFilter(menuItem.CommandString) || itemFilter(menuItem.Label))) - continue; - - if (!info.hbmpItem.IsNull && !Enum.IsDefined((HBITMAP_HMENU)((IntPtr)info.hbmpItem).ToInt64())) - { - using Bitmap? bitmap = Win32Helper.GetBitmapFromHBitmap(info.hbmpItem); - if (bitmap is not null) - { - bitmap.MakeTransparent(); - if (IconConverter.ConvertTo(bitmap, typeof(byte[])) is byte[] icon) - menuItem.Icon = icon; - } - } - - if (!info.hSubMenu.IsNull) - { - var subItems = new List(); - HMENU subMenu = info.hSubMenu; - menuItem.SubItems = subItems; - if (loadSubmenus) - LoadSubMenu(); - else - loadSubMenuActions.Add(subItems, LoadSubMenu); - - void LoadSubMenu() - { - try - { - if (Menu is IContextMenu2 contextMenu2) - contextMenu2.HandleMenuMsg(PInvoke.WM_INITMENUPOPUP, (WPARAM)(nuint)subMenu.Value, (LPARAM)(nint)index); - } - catch (Exception ex) when (ex is InvalidCastException or ArgumentException or COMException or NotImplementedException) - { - Debug.WriteLine(ex); - } - EnumMenuItems(subMenu, subItems, true); - } - } - } - - result.Add(menuItem); - } - finally - { - NativeMemory.Free(info.dwTypeData); - } - } - } - - public Task LoadSubMenu(List subItems) - { - if (!loadSubMenuActions.Remove(subItems, out Action? loadSubMenu)) - return Task.FromResult(false); - - return OwningThread.PostMethod(() => - { - try - { - loadSubMenu(); - return true; - } - catch - { - return false; - } - }); - } - - private static unsafe string? GetCommandString(IContextMenu contextMenu, uint offset) - { - // Avoid an AccessViolationException from handlers that return abnormally large command offsets, - // notably the "Run with graphics processor" menu item from NVIDIA. - if (offset > 5000) - return null; - - const int capacity = 512; - char* buffer = (char*)NativeMemory.AllocZeroed((nuint)capacity, sizeof(char)); - try - { - return contextMenu.GetCommandString(offset, PInvoke.GCS_VERBW, (PSTR)(byte*)buffer, capacity).Succeeded ? new string(buffer) : null; - } - catch (Exception ex) when (ex is InvalidCastException or ArgumentException or COMException or NotImplementedException) - { - Debug.WriteLine(ex); - return null; - } - finally - { - NativeMemory.Free(buffer); - } - } - - private void Dispose(bool disposing) - { - if (disposedValue) - return; - - if (disposing && Items is not null) - { - foreach (Win32ContextMenuItem item in Items) - (item as IDisposable)?.Dispose(); - } - - // Release the native menu on the worker's own STA thread. The message queue is FIFO, - // so cleanup completes before work posted by the next renter. - HMENU menuToDestroy = menu; - IContextMenu? contextMenuToRelease = contextMenu; - menu = default; - contextMenu = null; - OwningThread.PostMethod(() => - { - if (!menuToDestroy.IsNull) - PInvoke.DestroyMenu(menuToDestroy); - if ((object?)contextMenuToRelease is ComObject comObject) - comObject.FinalRelease(); - }); - ContextMenuWorkerPool.Return(worker); - disposedValue = true; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - ~ContextMenu() - { - Dispose(false); - } - } -} diff --git a/src/Files.App/Utils/Shell/ContextMenuItem.cs b/src/Files.App/Utils/Shell/ContextMenuItem.cs deleted file mode 100644 index 28878c5091e1..000000000000 --- a/src/Files.App/Utils/Shell/ContextMenuItem.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Utils.Shell -{ - /// - /// Represents an item for Win32 context menu. - /// - public partial class ContextMenuItem : Win32ContextMenuItem, IDisposable - { - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing && SubItems is not null) - { - foreach (var subItem in SubItems) - (subItem as IDisposable)?.Dispose(); - - SubItems = null; - } - } - } -} diff --git a/src/Files.App/Utils/Shell/ContextMenuWorkerPool.cs b/src/Files.App/Utils/Shell/ContextMenuWorkerPool.cs deleted file mode 100644 index 1179874b17d2..000000000000 --- a/src/Files.App/Utils/Shell/ContextMenuWorkerPool.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -namespace Files.App.Utils.Shell -{ - /// - /// Pools STA workers used to query Win32 shell context menus. - /// Reusing a worker keeps its apartment (and therefore the shell extension handlers loaded into it) - /// warm between right-clicks, instead of spinning up a fresh thread and cold-loading every handler - /// on each menu. - /// - internal static class ContextMenuWorkerPool - { - // The pool is bounded and workers are retired after a number of uses. This preserves the - // isolation the old thread-per-menu model gave for free: a shell extension that hangs or - // corrupts its apartment is confined to a single worker and cannot permanently degrade - // every future menu. - private const int MaxIdleWorkers = 3; - private const int MaxUsesPerWorker = 50; - - private static PoolState _idleWorkers = PoolState.Empty; - - private sealed class PoolState(Worker? head, int count) - { - internal static readonly PoolState Empty = new(null, 0); - - internal Worker? Head { get; } = head; - internal int Count { get; } = count; - } - - internal sealed class Worker(ThreadWithMessageQueue thread) - { - public ThreadWithMessageQueue Thread { get; } = thread; - - internal int Uses { get; set; } - internal Worker? Next { get; set; } - } - - /// - /// Borrows a warm worker from the pool, or creates one if none are idle. - /// - public static Worker Rent() - { - while (true) - { - PoolState state = Volatile.Read(ref _idleWorkers); - Worker? worker = state.Head; - - if (worker is null) - { - return new Worker(new ThreadWithMessageQueue()); - } - - var newState = new PoolState(worker.Next, state.Count - 1); - if (ReferenceEquals(Interlocked.CompareExchange(ref _idleWorkers, newState, state), state)) - { - worker.Next = null; - return worker; - } - } - } - - /// - /// Returns a worker to the pool once the caller has finished releasing the COM state it created - /// (which must happen on the worker's own thread). Over-used or excess workers are disposed. - /// - public static void Return(Worker worker) - { - worker.Uses++; - - if (worker.Uses >= MaxUsesPerWorker) - { - worker.Thread.Dispose(); - return; - } - - while (true) - { - PoolState state = Volatile.Read(ref _idleWorkers); - - if (state.Count >= MaxIdleWorkers) - { - worker.Thread.Dispose(); - return; - } - - worker.Next = state.Head; - var newState = new PoolState(worker, state.Count + 1); - - if (ReferenceEquals(Interlocked.CompareExchange(ref _idleWorkers, newState, state), state)) - { - return; - } - } - } - } -} diff --git a/src/Files.App/Utils/Shell/DetectionAndSharingHelper.cs b/src/Files.App/Utils/Shell/DetectionAndSharingHelper.cs deleted file mode 100644 index 5c99a315946f..000000000000 --- a/src/Files.App/Utils/Shell/DetectionAndSharingHelper.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - internal static class DetectionAndSharingHelper - { - public static unsafe NetworkAvailability GetNetworkAvailability() - { - IDetectionAndSharing dtsh = CreateDetectionAndSharing(); - var availability = NetworkAvailability.None; - - if (IsEnabled(dtsh, DTSH_TYPE.DTSH_NETWORK_DISCOVERY)) - availability |= NetworkAvailability.Discovery; - - if (IsEnabled(dtsh, DTSH_TYPE.DTSH_FILE_SHARING)) - availability |= NetworkAvailability.Sharing; - - return availability; - } - - public static unsafe void OpenNetworkSharingSettings() - { - HRESULT hr = PInvoke.CoCreateInstance(CLSID.CLSID_OpenControlPanel, null, CLSCTX.CLSCTX_INPROC_SERVER, out IOpenControlPanel? controlPanel); - ThrowIfFailed(hr, "Failed to create open control panel object."); - - fixed (char* name = "Microsoft.NetworkAndSharingCenter") - fixed (char* page = "Advanced") - { - hr = controlPanel!.Open(name, page, null); - ThrowIfFailed(hr, "Failed to open advanced sharing settings."); - } - } - - private static unsafe IDetectionAndSharing CreateDetectionAndSharing() - { - HRESULT hr = PInvoke.CoCreateInstance(CLSID.CLSID_DetectionAndSharing, null, CLSCTX.CLSCTX_INPROC_SERVER, out IDetectionAndSharing? dtsh); - ThrowIfFailed(hr, "Failed to create detection and sharing object."); - - return dtsh!; - } - - private static unsafe bool IsEnabled(IDetectionAndSharing dtsh, DTSH_TYPE type) - { - HRESULT hr = dtsh.GetStatus(type, out DTSH_STATE state, out _); - ThrowIfFailed(hr, $"Failed to get {type} status."); - - return state is DTSH_STATE.DTSH_ON; - } - - private static void ThrowIfFailed(HRESULT hr, string message) - { - if (hr.Failed) - throw new COMException(message, hr.Value); - } - } -} diff --git a/src/Files.App/Utils/Shell/Disposable.cs b/src/Files.App/Utils/Shell/Disposable.cs deleted file mode 100644 index bd9ab725a276..000000000000 --- a/src/Files.App/Utils/Shell/Disposable.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -namespace Files.App.Utils.Shell -{ - /// - /// Represents an abstracted implementation for IDisposable - /// - public abstract class Disposable : IDisposable - { - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - } - } -} diff --git a/src/Files.App/Utils/Shell/FileAssociationHelpers.cs b/src/Files.App/Utils/Shell/FileAssociationHelpers.cs deleted file mode 100644 index 3cce02dc8516..000000000000 --- a/src/Files.App/Utils/Shell/FileAssociationHelpers.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - public static class FileAssociationHelpers - { - // Known identifiers used by classic and AppX registrations for Microsoft Photos. - private static readonly string[] PhotosAssociationMarkers = - [ - "Microsoft.Windows.Photos", - "ms-photos", - "AppX43hnxtbyyps62jhe9sqpdzxn1790zetc" - ]; - - // PROGID and APPID are enough for modern default-app detection and cheaper than probing command/exe every time. - private static readonly ASSOCSTR[] PhotosAssociationSources = - [ - ASSOCSTR.ASSOCSTR_PROGID, - ASSOCSTR.ASSOCSTR_APPID, - ]; - - /// - /// Returns true when the specified extension is currently associated with Microsoft Photos. - /// - /// File extension with or without leading dot (e.g. ".jpg" or "jpg"). - public static bool IsMicrosoftPhotosDefaultAssociation(string? fileExtension) - { - if (string.IsNullOrWhiteSpace(fileExtension)) - return false; - - string normalizedExtension = fileExtension.StartsWith(".", StringComparison.Ordinal) - ? fileExtension - : $".{fileExtension}"; - - return IsMicrosoftPhotosDefaultAssociationCore(normalizedExtension); - } - - private static bool IsMicrosoftPhotosDefaultAssociationCore(string fileExtension) - { - - foreach (var source in PhotosAssociationSources) - { - if (TryGetAssociationString(fileExtension, source, out string value) && IsPhotosAssociationValue(value)) - return true; - } - - return false; - } - - private static bool IsPhotosAssociationValue(string associationValue) - => PhotosAssociationMarkers.Any(marker => associationValue.Contains(marker, StringComparison.OrdinalIgnoreCase)); - - private static unsafe bool TryGetAssociationString(string fileExtension, ASSOCSTR association, out string value) - { - value = string.Empty; - - try - { - fixed (char* pszAssoc = fileExtension) - { - PWSTR pwszAssoc = new(pszAssoc); - uint cchOutput = 0; - - // First call retrieves the required buffer length. - _ = PInvoke.AssocQueryString( - ASSOCF.ASSOCF_INIT_IGNOREUNKNOWN, - association, - pwszAssoc, - default, - default, - &cchOutput); - - if (cchOutput <= 1) - return false; - - char[] outputBuffer = new char[cchOutput]; - fixed (char* pszOutput = outputBuffer) - { - PWSTR pwszOutput = new(pszOutput); - - // Second call fills the buffer with the resolved association string. - var result = PInvoke.AssocQueryString( - ASSOCF.ASSOCF_INIT_IGNOREUNKNOWN, - association, - pwszAssoc, - default, - pwszOutput, - &cchOutput); - - if (result.Failed) - return false; - - value = pwszOutput.ToString(); - return !string.IsNullOrWhiteSpace(value); - } - } - } - catch - { - return false; - } - } - } -} diff --git a/src/Files.App/Utils/Shell/ItemStreamHelper.cs b/src/Files.App/Utils/Shell/ItemStreamHelper.cs deleted file mode 100644 index 065b892bd0c1..000000000000 --- a/src/Files.App/Utils/Shell/ItemStreamHelper.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Win32; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - public static class ItemStreamHelper - { - public static IShellItem? IShellItemFromPath(string path) - { - var hr = PInvoke.SHCreateItemFromParsingName(path, null!, out IShellItem psi); - return hr.Failed ? null : psi; - } - - public static IStream? IStreamFromPath(string path) - { - var hr = PInvoke.SHCreateStreamOnFileEx( - path, - (uint)(STGM.STGM_READ | STGM.STGM_FAILIFTHERE | STGM.STGM_SHARE_DENY_NONE), - 0, - false, - null, - out IStream pstm); - - return hr.Failed ? null : pstm; - } - } -} diff --git a/src/Files.App/Utils/Shell/LaunchHelper.cs b/src/Files.App/Utils/Shell/LaunchHelper.cs deleted file mode 100644 index b44691b64db4..000000000000 --- a/src/Files.App/Utils/Shell/LaunchHelper.cs +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using Microsoft.Extensions.Logging; -using System.IO; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - /// - /// Provides static helper for launching external executable files. - /// - public static class LaunchHelper - { - public unsafe static void LaunchSettings(string page) - { - PInvoke.CoCreateInstance(typeof(ApplicationActivationManager).GUID, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IApplicationActivationManager? pApplicationActivationManager); - - pApplicationActivationManager!.ActivateApplication( - "windows.immersivecontrolpanel_cw5n1h2txyewy!microsoft.windows.immersivecontrolpanel", - page, - ACTIVATEOPTIONS.AO_NONE, - out _); - } - - public static Task LaunchAppAsync(string application, string? arguments, string? workingDirectory) - { - return HandleApplicationLaunch(application, arguments, workingDirectory); - } - - public static Task RunCompatibilityTroubleshooterAsync(string filePath) - { - var compatibilityTroubleshooterAnswerFile = Path.Combine(Path.GetTempPath(), "CompatibilityTroubleshooterAnswerFile.xml"); - - try - { - File.WriteAllText(compatibilityTroubleshooterAnswerFile, $"CompatTab{filePath}"); - } - catch (IOException) - { - // Try with a different file name - SafetyExtensions.IgnoreExceptions(() => - { - compatibilityTroubleshooterAnswerFile = Path.Combine(Path.GetTempPath(), "CompatibilityTroubleshooterAnswerFile1.xml"); - File.WriteAllText(compatibilityTroubleshooterAnswerFile, $"CompatTab{filePath}"); - }); - } - - return HandleApplicationLaunch("MSDT.exe", $"/id PCWDiagnostic /af \"{compatibilityTroubleshooterAnswerFile}\"", ""); - } - - private static async Task HandleApplicationLaunch(string application, string? arguments, string? workingDirectory) - { - var currentWindows = Win32Helper.GetDesktopWindows(); - - if (FileExtensionHelpers.IsVhdFile(application)) - { - // Use PowerShell to mount Vhd Disk as this requires admin rights - return await Win32Helper.MountVhdDisk(application); - } - - var resolvedWorkingDirectory = string.IsNullOrEmpty(workingDirectory) ? PathNormalization.GetParentDir(application) : workingDirectory; - - try - { - using Process process = new Process(); - process.StartInfo.UseShellExecute = false; - process.StartInfo.FileName = application; - - // Show window if workingDirectory (opening terminal) - process.StartInfo.CreateNoWindow = string.IsNullOrEmpty(resolvedWorkingDirectory); - - if (arguments == "RunAs") - { - process.StartInfo.UseShellExecute = true; - process.StartInfo.Verb = "RunAs"; - - if (FileExtensionHelpers.IsMsiFile(application)) - { - process.StartInfo.FileName = "MSIEXEC.exe"; - process.StartInfo.Arguments = $"/a \"{application}\""; - } - } - else if (arguments == "RunAsUser") - { - process.StartInfo.UseShellExecute = true; - process.StartInfo.Verb = "RunAsUser"; - - if (FileExtensionHelpers.IsMsiFile(application)) - { - process.StartInfo.FileName = "MSIEXEC.exe"; - process.StartInfo.Arguments = $"/i \"{application}\""; - } - } - else - { - process.StartInfo.Arguments = arguments; - - // Refresh env variables for the child process - foreach (DictionaryEntry ent in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)) - { - string key = (string)ent.Key; - - // Skip USERNAME to avoid issues where files were executed as SYSTEM user (#12139) - if (string.Equals(key, "USERNAME", StringComparison.OrdinalIgnoreCase)) - continue; - - process.StartInfo.EnvironmentVariables[key] = (string)ent.Value!; - } - - foreach (DictionaryEntry ent in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)) - process.StartInfo.EnvironmentVariables[(string)ent.Key] = (string)ent.Value!; - - process.StartInfo.EnvironmentVariables["PATH"] = string.Join(';', - Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine), - Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User)); - } - - process.StartInfo.WorkingDirectory = resolvedWorkingDirectory; - process.Start(); - - Win32Helper.BringToForeground(currentWindows); - - return true; - } - catch (Win32Exception ex) when (ex.NativeErrorCode is 193 or 216 && FileExtensionHelpers.IsExecutableFile(application, exeOnly: true)) - { - // ERROR_EXE_MACHINE_TYPE_MISMATCH (216) - // "This app can't run on your PC" - await DialogDisplayHelper.ShowDialogAsync(DynamicDialogFactory.GetFor_CannotRunFileDialog()); - return false; - } - catch (Win32Exception) - { - using Process process = new Process(); - process.StartInfo.UseShellExecute = true; - process.StartInfo.FileName = application; - process.StartInfo.CreateNoWindow = true; - process.StartInfo.Arguments = arguments; - process.StartInfo.WorkingDirectory = resolvedWorkingDirectory; - - try - { - process.Start(); - - Win32Helper.BringToForeground(currentWindows); - - return true; - } - catch (Win32Exception ex) when (ex.NativeErrorCode == 50) - { - // ShellExecute return code 50 (ERROR_NOT_SUPPORTED) for some exes (#15179) - return Win32Helper.RunPowershellCommand($"& {Win32Helper.ToPowerShellStringLiteral(application)}", PowerShellExecutionOptions.Hidden); - } - catch (Win32Exception) - { - try - { - var opened = await STATask.Run(async () => - { - var split = application.Split('|').Where(x => !string.IsNullOrWhiteSpace(x)).Select(GetMtpPath).ToArray(); - if (split.Length == 1) - { - Process.Start(split[0]); - - Win32Helper.BringToForeground(currentWindows); - } - else - { - var pathsWithAssociations = new List<(string Path, string? Directory, string Association)>(split.Length); - foreach (var path in split) - { - var association = await Win32Helper.GetDefaultFileAssociationAsync(path) ?? Path.GetExtension(path); - pathsWithAssociations.Add((path, Path.GetDirectoryName(path), association)); - } - - foreach (var group in pathsWithAssociations.GroupBy(x => new { x.Directory, x.Association })) - { - if (!group.Any()) - continue; - - using var cMenu = await ContextMenu.GetContextMenuForFiles(group.Select(x => x.Path).ToArray(), PInvoke.CMF_DEFAULTONLY); - - if (cMenu is not null) - await cMenu.InvokeVerb("open"); - } - } - - return true; - }, App.Logger); - - if (!opened) - { - if (application.StartsWith(@"\\SHELL\", StringComparison.Ordinal)) - { - opened = await STATask.Run(async () => - { - using var cMenu = await ContextMenu.GetContextMenuForFiles(new[] { application }, PInvoke.CMF_DEFAULTONLY); - - if (cMenu is not null) - { - var menuItems = cMenu.Items - ?? throw new InvalidOperationException("The shell context menu has no item collection."); - await cMenu.InvokeItem(menuItems.FirstOrDefault()?.ID ?? -1); - } - - return true; - }, App.Logger); - } - } - - if (!opened) - { - var isAlternateStream = RegexHelpers.AlternateStream().IsMatch(application); - if (isAlternateStream) - { - var basePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("n")); - Directory.CreateDirectory(basePath); - - var tempPath = Path.Combine(basePath, new string(Path.GetFileName(application).SkipWhile(x => x != ':').Skip(1).ToArray())); - try - { - using var hFileSrc = PInvoke.CreateFile(application, (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_READ, FILE_SHARE_MODE.FILE_SHARE_READ | FILE_SHARE_MODE.FILE_SHARE_WRITE, null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_NORMAL, null); - using var hFileDst = PInvoke.CreateFile(tempPath, (uint)FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE, 0, null, FILE_CREATION_DISPOSITION.CREATE_ALWAYS, FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_NORMAL | FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_READONLY, null); - - if (!hFileSrc.IsInvalid && !hFileDst.IsInvalid) - { - // Copy ADS to temp folder and open - await using (var inStream = new FileStream(hFileSrc, FileAccess.Read)) - await using (var outStream = new FileStream(hFileDst, FileAccess.Write)) - { - await inStream.CopyToAsync(outStream); - await outStream.FlushAsync(); - } - - opened = await HandleApplicationLaunch(tempPath, arguments, workingDirectory); - } - } - finally - { - void DeleteTemporaryCopy() - { - if (File.Exists(tempPath)) - File.SetAttributes(tempPath, FileAttributes.Normal); - Directory.Delete(basePath, true); - } - - if (!opened) - { - SafetyExtensions.IgnoreExceptions(DeleteTemporaryCopy, App.Logger); - } - else - { - _ = Task.Run(async () => - { - for (var attempt = 0; attempt < 3; attempt++) - { - var delay = attempt switch - { - 0 => TimeSpan.FromMinutes(1), - 1 => TimeSpan.FromMinutes(5), - _ => TimeSpan.FromMinutes(30), - }; - await Task.Delay(delay); - if (SafetyExtensions.IgnoreExceptions(DeleteTemporaryCopy, App.Logger)) - return; - } - }); - } - } - } - } - - return opened; - } - catch (Win32Exception) - { - // Cannot open file (e.g DLL) - return false; - } - catch (ArgumentException) - { - // Cannot open file (e.g DLL) - return false; - } - } - } - catch (InvalidOperationException) - { - // Invalid file path - return false; - } - catch (Exception ex) - { - // Generic error, log - App.Logger.LogWarning(ex, $"Error launching: {LogPathHelper.RedactPath(application)}"); - return false; - } - } - - private static string GetMtpPath(string executable) - { - if (executable.StartsWith("\\\\?\\", StringComparison.Ordinal)) - { - using var computer = new ShellFolder(FOLDERID.FOLDERID_ComputerFolder); - using var device = computer.FirstOrDefault(i => - { - return i.Name is { } name && - executable.Replace("\\\\?\\", "", StringComparison.Ordinal).StartsWith(name, StringComparison.Ordinal); - }); - var deviceId = device?.ParsingName; - var itemPath = RegexHelpers.WindowsPath().Replace(executable, ""); - return deviceId is not null ? Path.Combine(deviceId, itemPath) : executable; - } - - return executable; - } - } -} diff --git a/src/Files.App/Utils/Shell/OpenWithMenu.cs b/src/Files.App/Utils/Shell/OpenWithMenu.cs deleted file mode 100644 index 6db1fcd73a90..000000000000 --- a/src/Files.App/Utils/Shell/OpenWithMenu.cs +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Files.App.Data.Items; -using System.Drawing; -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Gdi; -using Windows.Win32.System.Com; -using Windows.Win32.System.Memory; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Utils.Shell -{ - internal sealed partial class OpenWithMenu : IDisposable - { - private static readonly ImageConverter IconConverter = new(); - - private readonly ThreadWithMessageQueue owningThread; - private IContextMenu? contextMenu; - private HMENU menu; - private bool disposedValue; - - private OpenWithMenu(IContextMenu contextMenu, HMENU menu, ThreadWithMessageQueue owningThread) - { - this.contextMenu = contextMenu; - this.menu = menu; - this.owningThread = owningThread; - Items = []; - } - - public List Items { get; } - - public static async Task GetForFileAsync(string path) - { - var owningThread = new ThreadWithMessageQueue(); - var menu = await owningThread.PostMethod(() => - { - unsafe - { - return Create(path, owningThread); - } - }); - if (menu is null) - owningThread.Dispose(); - - return menu; - } - - public async Task InvokeItem(int itemId) - { - if (itemId < 0 || contextMenu is null) - return false; - - try - { - var currentWindows = Win32Helper.GetDesktopWindows(); - var hr = await owningThread.PostMethod(() => - { - return InvokeItemCore(itemId); - }); - if (hr.Failed) - return false; - - Win32Helper.BringToForeground(currentWindows); - - return true; - } - catch (Exception ex) when (ex is COMException or UnauthorizedAccessException) - { - Debug.WriteLine(ex); - } - - return false; - } - - private unsafe HRESULT InvokeItemCore(int itemId) - { - if (contextMenu is null) - return HRESULT.E_INVALIDARG; - - var commandInfo = new CMINVOKECOMMANDINFO - { - cbSize = (uint)sizeof(CMINVOKECOMMANDINFO), - lpVerb = (PCSTR)(byte*)(nuint)(uint)itemId, - nShow = (int)SHOW_WINDOW_CMD.SW_SHOWNORMAL, - }; - - return contextMenu.InvokeCommand(commandInfo); - } - - private static unsafe OpenWithMenu? Create(string path, ThreadWithMessageQueue owningThread) - { - IContextMenu? openWithContextMenu = null; - HMENU hMenu = default; - - try - { - HRESULT hr = PInvoke.CoCreateInstance(CLSID.CLSID_OpenWithMenu, null, CLSCTX.CLSCTX_INPROC_SERVER, out openWithContextMenu); - if (hr.ThrowIfFailedOnDebug().Failed || openWithContextMenu is null) - return null; - - if (openWithContextMenu is not IContextMenu2 openWithContextMenu2 || - openWithContextMenu is not IShellExtInit shellExtInit) - return null; - - hr = PInvoke.SHCreateItemFromParsingName(path, null, out IShellItem shellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - hr = shellItem.BindToHandler(null, PInvoke.BHID_DataObject, out IDataObject? dataObject); - if (hr.ThrowIfFailedOnDebug().Failed || dataObject is null) - return null; - - hr = shellExtInit.Initialize(null, dataObject, null); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - hMenu = PInvoke.CreatePopupMenu(); - hr = openWithContextMenu.QueryContextMenu(hMenu, 0, 1, 256, 0); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - HMENU hSubMenu = PInvoke.GetSubMenu(hMenu, 0); - if (hSubMenu.IsNull) - return null; - - hr = openWithContextMenu2.HandleMenuMsg(PInvoke.WM_INITMENUPOPUP, (WPARAM)(nuint)hSubMenu.Value, 0); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - var openWithMenu = new OpenWithMenu(openWithContextMenu, hMenu, owningThread); - openWithContextMenu = null; - hMenu = default; - openWithMenu.EnumMenuItems(hSubMenu); - - return openWithMenu; - } - catch (Exception ex) when (ex is COMException or UnauthorizedAccessException) - { - Debug.WriteLine(ex); - return null; - } - finally - { - if (!hMenu.IsNull) - PInvoke.DestroyMenu(hMenu); - } - } - - private unsafe void EnumMenuItems(HMENU hMenu) - { - uint count = unchecked((uint)PInvoke.GetMenuItemCount(hMenu)); - if (count is unchecked((uint)-1)) - return; - - for (uint index = 0; index < count; index++) - { - const uint bufferLength = 256; - MENUITEMINFOW menuItemInfo = default; - menuItemInfo.cbSize = (uint)sizeof(MENUITEMINFOW); - menuItemInfo.fMask = - MENU_ITEM_MASK.MIIM_BITMAP | - MENU_ITEM_MASK.MIIM_FTYPE | - MENU_ITEM_MASK.MIIM_ID | - MENU_ITEM_MASK.MIIM_STATE | - MENU_ITEM_MASK.MIIM_STRING; - menuItemInfo.dwTypeData = (char*)NativeMemory.Alloc(bufferLength, sizeof(char)); - menuItemInfo.cch = bufferLength; - - try - { - if (!PInvoke.GetMenuItemInfo(hMenu, index, true, &menuItemInfo)) - continue; - - var menuItem = new ContextMenuItem - { - ID = (int)(menuItemInfo.wID - 1), - Label = NormalizeLabel(menuItemInfo.dwTypeData.ToString()), - Type = (MENU_ITEM_TYPE)menuItemInfo.fType, - }; - - if (!menuItemInfo.hbmpItem.IsNull && !Enum.IsDefined(typeof(HBITMAP_HMENU), ((IntPtr)menuItemInfo.hbmpItem).ToInt64())) - { - using Bitmap? bitmap = GetBitmapFromHBitmap(menuItemInfo.hbmpItem); - if (bitmap is not null) - { - bitmap.MakeTransparent(); - if (IconConverter.ConvertTo(bitmap, typeof(byte[])) is byte[] icon) - menuItem.Icon = icon; - } - } - - Items.Add(menuItem); - } - finally - { - NativeMemory.Free(menuItemInfo.dwTypeData); - } - } - } - - private static Bitmap? GetBitmapFromHBitmap(HBITMAP hBitmap) - { - try - { - return Image.FromHbitmap((IntPtr)hBitmap); - } - catch - { - return null; - } - } - - private static string NormalizeLabel(string? rawLabel) - { - if (string.IsNullOrEmpty(rawLabel)) - return string.Empty; - - var labelBuilder = new System.Text.StringBuilder(rawLabel.Length); - - for (int i = 0; i < rawLabel.Length; i++) - { - char current = rawLabel[i]; - if (current != '&') - { - labelBuilder.Append(current); - continue; - } - - if (i + 1 >= rawLabel.Length) - { - labelBuilder.Append('&'); - continue; - } - - char next = rawLabel[++i]; - if (next == '&') - labelBuilder.Append('&'); - else - labelBuilder.Append(next); - } - - return labelBuilder.ToString(); - } - - public void Dispose() - { - if (disposedValue) - return; - - if (!menu.IsNull) - { - PInvoke.DestroyMenu(menu); - menu = default; - } - - contextMenu = null; - - owningThread.Dispose(); - disposedValue = true; - } - } -} diff --git a/src/Files.App/Utils/Shell/PreviewHandler.cs b/src/Files.App/Utils/Shell/PreviewHandler.cs deleted file mode 100644 index 49a2e14d3b0b..000000000000 --- a/src/Files.App/Utils/Shell/PreviewHandler.cs +++ /dev/null @@ -1,414 +0,0 @@ -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.UI; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Gdi; -using Windows.Win32.System.Com; -using Windows.Win32.System.Ole; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.PropertiesSystem; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Utils.Shell -{ - /// - /// Credits: https://github.com/GeeLaw/PreviewHost/ - /// - public sealed partial class PreviewHandler : IDisposable - { - [GeneratedComClass] - public sealed partial class PreviewHandlerFrame : IPreviewHandlerFrame - { - nint hwnd; - - public PreviewHandlerFrame(nint frame) - { - hwnd = frame; - } - - [return: MarshalAs(UnmanagedType.Error)] - public unsafe HRESULT GetWindowContext(PREVIEWHANDLERFRAMEINFO* pinfo) - { - pinfo->haccel = HACCEL.Null; - pinfo->cAccelEntries = 0; - return HRESULT.S_OK; - } - - [return: MarshalAs(UnmanagedType.Error)] - public unsafe HRESULT TranslateAccelerator(MSG* pmsg) - { - return HRESULT.S_FALSE; - } - } - - static COLORREF ColorRefFromColor(Color color) - { - return new COLORREF((((uint)color.B) << 16) | (((uint)color.G) << 8) | color.R); - } - - bool disposed; - bool init; - bool shown; - PreviewHandlerFrame? comSite; - HWND hwnd; - IPreviewHandler? previewHandler; - IPreviewHandlerVisuals? visuals; - - public PreviewHandler(Guid clsid, nint frame) - { - disposed = true; - init = false; - shown = false; - comSite = new PreviewHandlerFrame(frame); - hwnd = (HWND)frame; - try - { - SetupHandler(clsid); - disposed = false; - } - catch - { - previewHandler = null; - comSite = null; - throw; - } - } - - void SetupHandler(Guid clsid) - { - var cannotCreate = "Cannot create class " + clsid.ToString() + " as IPreviewHandler."; - var cannotCast = "Cannot cast class " + clsid.ToString() + " as IObjectWithSite."; - var cannotSetSite = "Cannot set site to the preview handler object."; - - HRESULT hr = PInvoke.CoCreateInstance(clsid, null, CLSCTX.CLSCTX_LOCAL_SERVER, out previewHandler); - - // See https://blogs.msdn.microsoft.com/adioltean/2005/06/24/when-cocreateinstance-returns-0x80080005-co_e_server_exec_failure/ - // CO_E_SERVER_EXEC_FAILURE also tends to happen when debugging in Visual Studio. - // Moreover, to create the instance in a server at low integrity level, we need - // to use another thread with low mandatory label. We keep it simple by creating - // a same-integrity object. - //if (hr.Value == E_SERVER_EXEC_FAILURE) - // hr = PInvoke.CoCreateInstance(clsid, null, CLSCTX.CLSCTX_LOCAL_SERVER, out previewHandlerObject); - - if (hr.Failed) - throw new COMException(cannotCreate, hr.Value); - - if (previewHandler is not IObjectWithSite objectWithSite) - throw new COMException(cannotCast, HRESULT.E_NOINTERFACE.Value); - - hr = objectWithSite.SetSite(comSite!); - if (hr.Failed) - throw new COMException(cannotSetSite, hr.Value); - - visuals = previewHandler as IPreviewHandlerVisuals; - } - - /// - /// Tries to initialize the preview handler with an IStream. - /// - /// This exception is thrown if IInitializeWithStream.Initialize fails for reason other than E_NOTIMPL. - /// Thrown if mode is neither Read nor ReadWrite. - /// The IStream interface used to initialize the preview handler. - /// The storage mode, must be Read or ReadWrite. - /// If the handler supports initialization with IStream, true; otherwise, false. - public bool InitWithStream(IStream stream, STGM mode) - { - if (mode != STGM.STGM_READ && mode != STGM.STGM_READWRITE) - throw new ArgumentOutOfRangeException("mode", mode, "The argument mode must be Read or ReadWrite."); - - if (previewHandler is not IInitializeWithStream initializeWithStream) - return false; - - HRESULT hr = initializeWithStream.Initialize(stream, (uint)mode); - if (hr == HRESULT.E_NOTIMPL) - return false; - if (hr.Failed) - throw new COMException("IInitializeWithStream.Initialize failed.", hr.Value); - - init = true; - - return true; - } - - /// - /// Same as InitWithStream(IStream, STGM). - /// - /// See InitWithStream(IStream, STGM). - /// See InitWithStream(IStream, STGM). - /// The IShellItem interface used to initialize the preview handler. - /// The storage mode. - /// True or false, see InitWithStream(IStream, STGM). - public bool InitWithItem(IShellItem psi, STGM mode) - { - EnsureNotDisposed(); - EnsureNotInitialized(); - - if (mode != STGM.STGM_READ && mode != STGM.STGM_READWRITE) - throw new ArgumentOutOfRangeException("mode", mode, "The argument mode must be Read or ReadWrite."); - - if (previewHandler is not IInitializeWithItem initializeWithItem) - return false; - - HRESULT hr = initializeWithItem.Initialize(psi, (uint)mode); - if (hr == HRESULT.E_NOTIMPL) - return false; - if (hr.Failed) - throw new COMException("IInitializeWithItem.Initialize failed.", hr.Value); - - init = true; - - return true; - } - - /// - /// Same as InitWithStream(IStream, STGM). - /// - /// See InitWithStream(IStream, STGM). - /// See InitWithStream(IStream, STGM). - /// The path to the file. - /// The storage mode. - /// True or false, see InitWithStream(IStream, STGM). - public bool InitWithFile(string path, STGM mode) - { - EnsureNotDisposed(); - EnsureNotInitialized(); - - if (mode != STGM.STGM_READ && mode != STGM.STGM_READWRITE) - throw new ArgumentOutOfRangeException("mode", mode, "The argument mode must be Read or ReadWrite."); - - if (previewHandler is not IInitializeWithFile initializeWithFile) - return false; - - HRESULT hr = initializeWithFile.Initialize(path, (uint)mode); - if (hr == HRESULT.E_NOTIMPL) - return false; - if (hr.Failed) - throw new COMException("IInitializeWithFile.Initialize failed.", hr.Value); - - init = true; - - return true; - } - - /// - /// Tries each way to initialize the object with a file. - /// - /// The file name. - /// If initialization was successful, true; otherwise, an exception is thrown. - public bool InitWithFileWithEveryWay(string path) - { - var exceptions = new List(); - // Why should we try IStream first? - // Because that gives us the best security. - // If we initialize with string or IShellItem, - // we have no control over how the preview handler - // opens the file, which might decide to open the - // file for read/write exclusively. - try - { - var stream = ItemStreamHelper.IStreamFromPath(path); - if (stream is not null && InitWithStream(stream, STGM.STGM_READ)) - return true; - } - catch (Exception ex) - { - exceptions.Add(ex); - } - - // Next try file because that could save us some P/Invokes. - try - { - if (InitWithFile(path, STGM.STGM_READ)) - return true; - } - catch (Exception ex) - { - exceptions.Add(ex); - } - try - { - var shellItem = ItemStreamHelper.IShellItemFromPath(path); - if (shellItem is not null && InitWithItem(shellItem, STGM.STGM_READ)) - return true; - if (exceptions.Count == 0) - throw new NotSupportedException("The object cannot be initialized at all."); - } - catch (Exception ex) - { - exceptions.Add(ex); - } - - throw new AggregateException(exceptions); - } - - /// - /// Calls IPreviewHandler.SetWindow. - /// - public bool ResetWindow() - { - EnsureNotDisposed(); - //EnsureInitialized(); - if (!init) - return false; - var hr = previewHandler.SetWindow(hwnd, new RECT()); - return hr >= 0; - } - - /// - /// Calls IPreviewHandler.SetRect. - /// - public bool ResetBounds(RECT previewerBounds) - { - EnsureNotDisposed(); - //EnsureInitialized(); - if (!init) - return false; - var hr = previewHandler.SetRect(previewerBounds); - return hr >= 0; - } - - /// - /// Sets the background if the handler implements IPreviewHandlerVisuals. - /// - /// The background color. - /// Whether the call succeeds. - public bool SetBackground(Color color) - { - var hr = visuals?.SetBackgroundColor(ColorRefFromColor(color)); - return hr.HasValue && hr.Value >= 0; - } - - /// - /// Sets the text color if the handler implements IPreviewHandlerVisuals. - /// - /// The text color. - /// Whether the call succeeds. - public bool SetForeground(Color color) - { - var hr = visuals?.SetTextColor(ColorRefFromColor(color)); - return hr.HasValue && hr.Value >= 0; - } - - /// - /// Sets the font if the handler implements IPreviewHandlerVisuals. - /// - /// The LogFontW reference. - /// Whether the call succeeds. - public unsafe bool SetFont(nint font) - { - var hr = visuals?.SetFont(*(LOGFONTW*)font); - return hr.HasValue && hr.Value >= 0; - } - - /// - /// Shows the preview if the object has been successfully initialized. - /// - public void DoPreview() - { - EnsureNotDisposed(); - //EnsureInitialized(); - if (!init) - return; - EnsureNotShown(); - ResetWindow(); - previewHandler?.DoPreview(); - shown = true; - } - - /// - /// Tells the preview handler to set focus to itself. - /// - public void Focus() - { - EnsureNotDisposed(); - //EnsureInitialized(); - if (!init) - return; - EnsureShown(); - previewHandler?.SetFocus(); - } - - /// - /// Tells the preview handler to query focus. - /// - /// The focused window. - public nint QueryFocus() - { - EnsureNotDisposed(); - //EnsureInitialized(); - if (!init) - return IntPtr.Zero; - EnsureShown(); - - var hr = previewHandler.QueryFocus(out var result); - if (hr < 0) - return IntPtr.Zero; - - return (nint)result; - } - - void EnsureNotDisposed() - { - if (disposed) - throw new ObjectDisposedException("PreviewHandler"); - } - - void EnsureInitialized() - { - if (!init) - throw new InvalidOperationException("Object must be initialized before calling this method."); - } - - void EnsureNotInitialized() - { - if (init) - throw new InvalidOperationException("Object is already initialized and cannot be initialized again."); - } - - void EnsureShown() - { - if (!shown) - throw new InvalidOperationException("The preview handler must be shown to call this method."); - } - - void EnsureNotShown() - { - if (shown) - throw new InvalidOperationException("The preview handler must not be shown to call this method."); - } - - #region IDisposable pattern - - public void Dispose() - { - if (disposed) - return; - disposed = true; - init = false; - - try - { - previewHandler?.Unload(); - - // Break the site connection so the handler releases the PreviewHandlerFrame wrapper deterministically - if (previewHandler is IObjectWithSite objectWithSite) - objectWithSite.SetSite(null!); - } - catch (COMException) - { - // RPC errors (e.g. RPC_S_SERVER_UNAVAILABLE) when the prevhost process already exited - } - - if ((object?)previewHandler is ComObject comObject) - comObject.FinalRelease(); - - previewHandler = null; - visuals = null; - comSite = null; - } - - #endregion - - } -} diff --git a/src/Files.App/Utils/Shell/ShellDataObject.cs b/src/Files.App/Utils/Shell/ShellDataObject.cs deleted file mode 100644 index a3a9f6f3f46f..000000000000 --- a/src/Files.App/Utils/Shell/ShellDataObject.cs +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.System.Com; -using Windows.Win32.System.Memory; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; - -namespace Files.App.Utils.Shell -{ - /// - /// Creates and reads Shell data objects used by clipboard and drag-and-drop operations. - /// - public static unsafe class ShellDataObject - { - private const ushort CfHDrop = 15; - private const int ClipboardRetryCount = 10; - private const int ClipboardRetryDelay = 100; - internal const string ShellIdListArrayFormat = "Shell IDList Array"; - private const string PreferredDropEffectFormat = "Preferred DropEffect"; - private const string FileGroupDescriptorFormat = "FileGroupDescriptorW"; - private const string FileContentsFormat = "FileContents"; - - public readonly record struct FileDescriptor(string Name, FILE_FLAGS_AND_ATTRIBUTES Attributes); - - /// Creates a Shell data object for the supplied items. - public static IDataObject Create(IReadOnlyList items) - { - ArgumentOutOfRangeException.ThrowIfZero(items.Count); - using ShellItem? commonParent = GetCommonParent(items); - ITEMIDLIST* parentPidl; - if (commonParent is not null) - { - PInvoke.SHGetIDListFromObject(commonParent.IShellItem, out parentPidl).ThrowOnFailure(); - } - else - { - PInvoke.SHGetDesktopFolder(out IShellFolder? desktop).ThrowOnFailure(); - PInvoke.SHGetIDListFromObject(desktop!, out parentPidl).ThrowOnFailure(); - } - - ITEMIDLIST** itemPidls = null; - ITEMIDLIST** dataObjectPidls = null; - try - { - itemPidls = (ITEMIDLIST**)NativeMemory.AllocZeroed((nuint)items.Count, (nuint)sizeof(ITEMIDLIST*)); - dataObjectPidls = (ITEMIDLIST**)NativeMemory.AllocZeroed((nuint)items.Count, (nuint)sizeof(ITEMIDLIST*)); - for (int index = 0; index < items.Count; index++) - { - PInvoke.SHGetIDListFromObject(items[index].IShellItem, out itemPidls[index]).ThrowOnFailure(); - // SHCreateDataObject expects single child PIDLs when the items share a parent. - dataObjectPidls[index] = commonParent is null ? itemPidls[index] : PInvoke.ILFindLastID(itemPidls[index]); - } - - Guid interfaceId = typeof(IDataObject).GUID; - PInvoke.SHCreateDataObject(parentPidl, (uint)items.Count, dataObjectPidls, null!, &interfaceId, out object dataObject).ThrowOnFailure(); - return (IDataObject)dataObject; - } - finally - { - if (itemPidls is not null) - { - for (int index = 0; index < items.Count; index++) - PInvoke.CoTaskMemFree(itemPidls[index]); - } - NativeMemory.Free(dataObjectPidls); - NativeMemory.Free(itemPidls); - PInvoke.CoTaskMemFree(parentPidl); - } - } - - /// Places file system paths on the clipboard with the specified preferred drop effect. - public static void SetClipboard(IReadOnlyList paths, uint preferredDropEffect) - { - var items = new List(paths.Count); - try - { - foreach (string path in paths) - items.Add(new(path)); - - IDataObject dataObject = Create(items); - SetFileDropList(dataObject, paths); - SetData(dataObject, PreferredDropEffectFormat, preferredDropEffect); - SetClipboard(dataObject); - } - finally - { - foreach (ShellItem item in items) - item.Dispose(); - } - } - - private static ShellItem? GetCommonParent(IReadOnlyList items) - { - ShellItem? commonParent = items[0].Parent; - if (commonParent is null) - return null; - - try - { - ShellPidl commonParentPidl = commonParent.PIDL; - for (int index = 1; index < items.Count; index++) - { - using ShellItem? parent = items[index].Parent; - if (parent is null || !parent.PIDL.Equals(commonParentPidl)) - { - commonParent.Dispose(); - return null; - } - } - - return commonParent; - } - catch - { - commonParent.Dispose(); - throw; - } - } - - /// Reads the Shell IDList Array clipboard payload from a data object. - public static byte[]? GetShellIdListArray(IDataObject dataObject) - { - if (!TryGetData(dataObject, ShellIdListArrayFormat, -1, TYMED.TYMED_HGLOBAL, out STGMEDIUM medium)) - return null; - - void* data = null; - try - { - data = PInvoke.GlobalLock(medium.u.hGlobal); - nuint size = PInvoke.GlobalSize(medium.u.hGlobal); - if (data is null || size is 0 || size > int.MaxValue) - return null; - - byte[] result = new byte[(int)size]; - Marshal.Copy((nint)data, result, 0, result.Length); - return result; - } - finally - { - if (data is not null) - PInvoke.GlobalUnlock(medium.u.hGlobal); - PInvoke.ReleaseStgMedium(ref medium); - } - } - - /// Gets the current OLE clipboard data object. - public static IDataObject? GetClipboard() - => PInvoke.OleGetClipboard(out IDataObject dataObject).Succeeded ? dataObject : null; - - /// Reads virtual-file descriptors from a clipboard data object. - public static IReadOnlyList GetFileDescriptors(IDataObject dataObject) - { - if (!TryGetData(dataObject, FileGroupDescriptorFormat, -1, TYMED.TYMED_HGLOBAL, out STGMEDIUM medium)) - return []; - - void* data = null; - try - { - data = PInvoke.GlobalLock(medium.u.hGlobal); - if (data is null) - return []; - - FILEGROUPDESCRIPTORW* group = (FILEGROUPDESCRIPTORW*)data; - nuint dataSize = PInvoke.GlobalSize(medium.u.hGlobal); - if (group->cItems > int.MaxValue || (nuint)FILEGROUPDESCRIPTORW.SizeOf((int)group->cItems) > dataSize) - return []; - - var descriptors = new List((int)group->cItems); - for (int index = 0; index < group->cItems; index++) - { - ref FILEDESCRIPTORW descriptor = ref group->fgd[index]; - descriptors.Add(new(descriptor.cFileName.ToString(), (FILE_FLAGS_AND_ATTRIBUTES)descriptor.dwFileAttributes)); - } - return descriptors; - } - finally - { - if (data is not null) - PInvoke.GlobalUnlock(medium.u.hGlobal); - PInvoke.ReleaseStgMedium(ref medium); - } - } - - /// Gets a virtual file-content stream and transfers ownership of its storage medium to the caller. - public static bool TryGetFileContents(IDataObject dataObject, int index, out IStream? stream, out STGMEDIUM medium) - { - stream = null; - if (!TryGetData(dataObject, FileContentsFormat, index, TYMED.TYMED_ISTREAM, out medium) || medium.u.pstm is null) - return false; - - try - { - stream = UniqueComInterfaceMarshaller.ConvertToManaged(medium.u.pstm); - } - catch - { - PInvoke.ReleaseStgMedium(ref medium); - medium = default; - throw; - } - if (stream is not null) - return true; - - PInvoke.ReleaseStgMedium(ref medium); - medium = default; - return false; - } - - private static bool TryGetData(IDataObject dataObject, string formatName, int index, TYMED mediumType, out STGMEDIUM medium) - { - uint format = PInvoke.RegisterClipboardFormat(formatName); - FORMATETC formatEtc = new() - { - cfFormat = checked((ushort)format), - dwAspect = (uint)DVASPECT.DVASPECT_CONTENT, - lindex = index, - tymed = (uint)mediumType, - }; - if (dataObject.GetData(formatEtc, out medium).Failed) - return false; - - if (medium.tymed == mediumType) - return true; - - PInvoke.ReleaseStgMedium(ref medium); - medium = default; - return false; - } - - private static void SetData(IDataObject dataObject, string formatName, uint value) - { - HGLOBAL data = PInvoke.GlobalAlloc(GLOBAL_ALLOC_FLAGS.GMEM_MOVEABLE, sizeof(uint)); - if (data.IsNull) - throw new OutOfMemoryException(); - - bool transferred = false; - try - { - uint* dataPointer = (uint*)PInvoke.GlobalLock(data); - if (dataPointer is null) - throw new OutOfMemoryException(); - try - { - *dataPointer = value; - } - finally - { - PInvoke.GlobalUnlock(data); - } - - SetData(dataObject, checked((ushort)PInvoke.RegisterClipboardFormat(formatName)), data); - transferred = true; - } - finally - { - if (!transferred) - PInvoke.GlobalFree(data); - } - } - - private static void SetFileDropList(IDataObject dataObject, IReadOnlyList paths) - { - int characterCount = 1; - foreach (string path in paths) - characterCount = checked(characterCount + path.Length + 1); - - nuint dataSize = checked((nuint)sizeof(DROPFILES) + (nuint)characterCount * sizeof(char)); - HGLOBAL data = PInvoke.GlobalAlloc(GLOBAL_ALLOC_FLAGS.GMEM_MOVEABLE, dataSize); - if (data.IsNull) - throw new OutOfMemoryException(); - - bool transferred = false; - try - { - DROPFILES* dropFiles = (DROPFILES*)PInvoke.GlobalLock(data); - if (dropFiles is null) - throw new OutOfMemoryException(); - try - { - *dropFiles = new() - { - pFiles = (uint)sizeof(DROPFILES), - fWide = true, - }; - char* destination = (char*)((byte*)dropFiles + dropFiles->pFiles); - foreach (string path in paths) - { - path.AsSpan().CopyTo(new Span(destination, path.Length)); - destination += path.Length; - *destination++ = '\0'; - } - *destination = '\0'; - } - finally - { - PInvoke.GlobalUnlock(data); - } - - SetData(dataObject, CfHDrop, data); - transferred = true; - } - finally - { - if (!transferred) - PInvoke.GlobalFree(data); - } - } - - private static void SetData(IDataObject dataObject, ushort formatId, HGLOBAL data) - { - FORMATETC format = new() - { - cfFormat = formatId, - dwAspect = (uint)DVASPECT.DVASPECT_CONTENT, - lindex = -1, - tymed = (uint)TYMED.TYMED_HGLOBAL, - }; - STGMEDIUM medium = new() - { - tymed = TYMED.TYMED_HGLOBAL, - u = new() { hGlobal = data }, - }; - dataObject.SetData(format, medium, true).ThrowOnFailure(); - } - - private static void SetClipboard(IDataObject dataObject) - { - HRESULT result = default; - for (int attempt = 0; attempt < ClipboardRetryCount; attempt++) - { - result = PInvoke.OleSetClipboard(dataObject); - if (result.Succeeded) - { - result = PInvoke.OleFlushClipboard(); - if (result.Succeeded) - return; - } - - if (attempt + 1 < ClipboardRetryCount) - Thread.Sleep(ClipboardRetryDelay); - } - - result.ThrowOnFailure(); - } - } -} diff --git a/src/Files.App/Utils/Shell/ShellFileOperations2.cs b/src/Files.App/Utils/Shell/ShellFileOperations2.cs deleted file mode 100644 index 8cbe434576be..000000000000 --- a/src/Files.App/Utils/Shell/ShellFileOperations2.cs +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.ComponentModel; -using System.IO; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - /// - /// Queues Shell file operations and exposes their progress callbacks. - /// - public sealed unsafe partial class ShellFileOperations2 : IDisposable - { - private IFileOperation? operation; - private readonly IFileOperationProgressSink sink; - private readonly uint sinkCookie; - private FILEOPERATION_FLAGS options = FILEOPERATION_FLAGS.FOF_ALLOWUNDO | FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR; - private HWND ownerWindow; - - /// Initializes a new instance of the class. - /// The window that owns the modal dialog. This value can be . - public ShellFileOperations2(HWND owner = default) - { - // Use CLSCTX_LOCAL_SERVER to prevent the elevation dialog from appearing behind the app window. - PInvoke.CoCreateInstance(typeof(FileOperation).GUID, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IFileOperation? fileOperation).ThrowOnFailure(); - operation = fileOperation; - Operation.SetOperationFlags(options).ThrowOnFailure(); - if (!owner.IsNull) - Operation.SetOwnerWindow(owner).ThrowOnFailure(); - - sink = new OperationSink(this); - Operation.Advise(sink, out sinkCookie).ThrowOnFailure(); - } - - private IFileOperation Operation => operation ?? throw new ObjectDisposedException(nameof(ShellFileOperations2)); - - /// Occurs after the last queued operation is complete. - public event EventHandler? FinishOperations; - - /// Occurs after an item has been copied. - public event EventHandler? PostCopyItem; - - /// Occurs after an item has been deleted. - public event EventHandler? PostDeleteItem; - - /// Occurs after an item has been moved. - public event EventHandler? PostMoveItem; - - /// Occurs after a new item has been created. - public event EventHandler? PostNewItem; - - /// Occurs after an item has been renamed. - public event EventHandler? PostRenameItem; - - /// Occurs before an item is copied. - public event EventHandler? PreCopyItem; - - /// Occurs before an item is deleted. - public event EventHandler? PreDeleteItem; - - /// Occurs before an item is moved. - public event EventHandler? PreMoveItem; - - /// Occurs before a new item is created. - public event EventHandler? PreNewItem; - - /// Occurs before an item is renamed. - public event EventHandler? PreRenameItem; - - /// Occurs before any queued file operation is performed. - public event EventHandler? StartOperations; - - /// Occurs when the operation reports progress. - public event ProgressChangedEventHandler? UpdateProgress; - - /// Gets or sets options that control file operations. - public FILEOPERATION_FLAGS Options - { - get => options; - set - { - if (value == options) - return; - Operation.SetOperationFlags(value).ThrowOnFailure(); - options = value; - } - } - - /// Gets or sets the parent window for progress and error dialogs. - public HWND OwnerWindow - { - get => ownerWindow; - set - { - Operation.SetOwnerWindow(value).ThrowOnFailure(); - ownerWindow = value; - } - } - - /// Gets the number of queued operations. - public int QueuedOperations { get; private set; } - - /// Queues an item to be copied to a destination folder. - public void QueueCopyOperation(ShellItem source, ShellFolder destination, string? newName = null) - { - fixed (char* name = newName) - Operation.CopyItem(source.IShellItem, destination.IShellItem, name, null!).ThrowOnFailure(); - QueuedOperations++; - } - - /// Queues an item for deletion. - public void QueueDeleteOperation(ShellItem item) - { - Operation.DeleteItem(item.IShellItem, null!).ThrowOnFailure(); - QueuedOperations++; - } - - /// Queues an item to be moved to a destination folder. - public void QueueMoveOperation(ShellItem source, ShellFolder destination, string? newName = null) - { - fixed (char* name = newName) - Operation.MoveItem(source.IShellItem, destination.IShellItem, name, null!).ThrowOnFailure(); - QueuedOperations++; - } - - /// Queues a new item to be created in a destination folder. - public void QueueNewItemOperation(ShellFolder destination, string name, FileAttributes attributes = FileAttributes.Normal, string? template = null) - { - fixed (char* itemName = name, templateName = template) - Operation.NewItem(destination.IShellItem, (uint)attributes, itemName, templateName, null!).ThrowOnFailure(); - QueuedOperations++; - } - - /// Queues an item to be given a new display name. - public void QueueRenameOperation(ShellItem source, string newName) - { - fixed (char* name = newName) - Operation.RenameItem(source.IShellItem, name, null!).ThrowOnFailure(); - QueuedOperations++; - } - - /// Executes all queued operations. - public void PerformOperations() - { - Operation.PerformOperations().ThrowOnFailure(); - QueuedOperations = 0; - } - - /// - public void Dispose() - { - if (operation is null) - return; - - operation.Unadvise(sinkCookie); - operation = null; - GC.SuppressFinalize(this); - } - - [GeneratedComClass] - private sealed partial class OperationSink : IFileOperationProgressSink - { - private readonly WeakReference operationsReference; - - public OperationSink(ShellFileOperations2 operations) - { - operationsReference = new(operations); - } - - public HRESULT StartOperations() => Raise(operations => operations.StartOperations?.Invoke(operations, EventArgs.Empty)); - - public HRESULT FinishOperations(HRESULT result) => Raise(operations => operations.FinishOperations?.Invoke(operations, new(result: result))); - - public HRESULT PreRenameItem(uint flags, IShellItem source, PCWSTR newName) => Raise(operations => operations.PreRenameItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, name: newName.ToString()))); - - public HRESULT PostRenameItem(uint flags, IShellItem source, PCWSTR newName, HRESULT result, IShellItem newlyCreated) => Raise(operations => operations.PostRenameItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, destination: newlyCreated, name: newName.ToString(), result: result))); - - public HRESULT PreMoveItem(uint flags, IShellItem source, IShellItem destinationFolder, PCWSTR newName) => Raise(operations => operations.PreMoveItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, destinationFolder, name: newName.ToString()))); - - public HRESULT PostMoveItem(uint flags, IShellItem source, IShellItem destinationFolder, PCWSTR newName, HRESULT result, IShellItem newlyCreated) => Raise(operations => operations.PostMoveItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, destinationFolder, newlyCreated, newName.ToString(), result))); - - public HRESULT PreCopyItem(uint flags, IShellItem source, IShellItem destinationFolder, PCWSTR newName) => Raise(operations => operations.PreCopyItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, destinationFolder, name: newName.ToString()))); - - public HRESULT PostCopyItem(uint flags, IShellItem source, IShellItem destinationFolder, PCWSTR newName, HRESULT result, IShellItem newlyCreated) => Raise(operations => operations.PostCopyItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, destinationFolder, newlyCreated, newName.ToString(), result))); - - public HRESULT PreDeleteItem(uint flags, IShellItem source) => Raise(operations => operations.PreDeleteItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source))); - - public HRESULT PostDeleteItem(uint flags, IShellItem source, HRESULT result, IShellItem newlyCreated) => Raise(operations => operations.PostDeleteItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, source, destination: newlyCreated, result: result))); - - public HRESULT PreNewItem(uint flags, IShellItem destinationFolder, PCWSTR newName) => Raise(operations => operations.PreNewItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, destinationFolder: destinationFolder, name: newName.ToString()))); - - public HRESULT PostNewItem(uint flags, IShellItem destinationFolder, PCWSTR newName, PCWSTR templateName, uint attributes, HRESULT result, IShellItem newItem) => Raise(operations => operations.PostNewItem?.Invoke(operations, new((_TRANSFER_SOURCE_FLAGS)flags, destinationFolder, newItem, newName.ToString(), result, templateName.ToString(), attributes))); - - public HRESULT UpdateProgress(uint workTotal, uint workCompleted) => Raise(operations => operations.UpdateProgress?.Invoke(operations, new(workTotal is 0 ? 0 : workCompleted * 100.0 / workTotal, null))); - - public HRESULT ResetTimer() => HRESULT.E_NOTIMPL; - public HRESULT PauseTimer() => HRESULT.E_NOTIMPL; - public HRESULT ResumeTimer() => HRESULT.E_NOTIMPL; - - private HRESULT Raise(Action action) - { - if (!operationsReference.TryGetTarget(out ShellFileOperations2? operations)) - return HRESULT.E_FAIL; - - try - { - action(operations); - return HRESULT.S_OK; - } - catch (COMException exception) - { - return new(exception.ErrorCode); - } - catch (Win32Exception exception) - { - int error = exception.NativeErrorCode; - return new(error <= 0 ? error : unchecked((int)(0x80070000u | ((uint)error & 0xFFFFu)))); - } - catch (Exception exception) - { - return new(exception.HResult); - } - } - } - - /// Arguments supplied to Shell file-operation events. - public class ShellFileOpEventArgs : EventArgs - { - internal ShellFileOpEventArgs(_TRANSFER_SOURCE_FLAGS flags = _TRANSFER_SOURCE_FLAGS.TSF_NORMAL, IShellItem? source = null, IShellItem? destinationFolder = null, IShellItem? destination = null, string? name = null, HRESULT result = default) - { - Flags = flags; - if (source is not null) - SourceItem = ShellItem.Open(source); - if (destinationFolder is not null) - DestFolder = ShellItem.Open(destinationFolder); - if (destination is not null) - DestItem = ShellItem.Open(destination); - Name = name; - Result = result; - } - - /// Gets the destination folder. - public ShellItem? DestFolder { get; } - - /// Gets the destination item. - public ShellItem? DestItem { get; } - - /// Gets the transfer flags. - public _TRANSFER_SOURCE_FLAGS Flags { get; } - - /// Gets the item name. - public string? Name { get; } - - /// Gets the operation result. - public HRESULT Result { get; } - - /// Gets the source item. - public ShellItem? SourceItem { get; } - } - - /// Arguments supplied to the event. - public sealed class ShellFileNewOpEventArgs : ShellFileOpEventArgs - { - internal ShellFileNewOpEventArgs(_TRANSFER_SOURCE_FLAGS flags, IShellItem destinationFolder, IShellItem destination, string name, HRESULT result, string? template, uint attributes) : base(flags, null, destinationFolder, destination, name, result) - { - TemplateName = template; - FileAttributes = (FileAttributes)attributes; - } - - /// Gets the template name. - public string? TemplateName { get; } - - /// Gets the attributes of the new item. - public FileAttributes FileAttributes { get; } - } - - public delegate void ProgressChangedEventHandler(object? sender, ProgressChangedEventArgs e); - - /// Provides the percentage and state for a progress update. - public sealed class ProgressChangedEventArgs(double progressPercentage, object? userState) : EventArgs - { - public double ProgressPercentage { get; } = progressPercentage; - public object? UserState { get; } = userState; - } - } -} diff --git a/src/Files.App/Utils/Shell/ShellFolderExtensions.cs b/src/Files.App/Utils/Shell/ShellFolderExtensions.cs deleted file mode 100644 index e5ae5f47f530..000000000000 --- a/src/Files.App/Utils/Shell/ShellFolderExtensions.cs +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using System.Runtime.InteropServices.ComTypes; -using Windows.Win32.System.SystemServices; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - /// - /// Provides static extension for shell folders. - /// - public static class ShellFolderExtensions - { - public static ShellLibraryItem GetShellLibraryItem(ShellLibraryEx library, string filePath) - { - var libraryItem = new ShellLibraryItem - { - FullPath = filePath, - AbsolutePath = library.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING) ?? string.Empty, - RelativePath = library.GetDisplayName(SIGDN.SIGDN_PARENTRELATIVEPARSING) ?? string.Empty, - DisplayName = library.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY) ?? string.Empty, - IsPinned = library.PinnedToNavigationPane, - }; - - var folders = library.Folders; - if (folders.Count > 0) - { - libraryItem.DefaultSaveFolder = SafetyExtensions.IgnoreExceptions(() => library.DefaultSaveFolder.FileSystemPath) ?? string.Empty; - libraryItem.Folders = folders.Select(f => f.FileSystemPath).OfType().ToArray(); - } - - return libraryItem; - } - - private static T? TryGetProperty(this ShellItemPropertyStore propertyStore, string propertyName) - { - T? value = default; - SafetyExtensions.IgnoreExceptions(() => propertyStore.TryGetValue(propertyName, out value)); - return value; - } - - public static ShellFileItem? GetShellFileItem(ShellItem? folderItem) - { - if (folderItem is null) - return null; - - // NOTE: Query only the required attributes because some shell folders do not implement the full attribute set - - // Zip archives are also shell folders, check for STREAM attribute - - bool isFolder = folderItem.IsFolder && !folderItem.IsStream; - var parsingPath = folderItem.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING); - - // True path on disk - parsingPath ??= folderItem.FileSystemPath; - - if (parsingPath is null || !Path.IsPathRooted(parsingPath)) - { - parsingPath = parsingPath switch - { - "::{645FF040-5081-101B-9F08-00AA002F954E}" => Constants.UserEnvironmentPaths.RecycleBinPath, - "::{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}" => Constants.UserEnvironmentPaths.NetworkFolderPath, - "::{208D2C60-3AEA-1069-A2D7-08002B30309D}" => Constants.UserEnvironmentPaths.NetworkFolderPath, - "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" => Constants.UserEnvironmentPaths.MyComputerPath, - "::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Documents.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath), - "::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Pictures.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath), - "::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Music.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath), - "::{031E4825-7B94-4DC3-B131-E946B44C8DD5}\\Videos.library-ms" => ShellHelpers.GetLibraryFullPathFromShell(parsingPath), - // Use PIDL as path - // Replace "/" with "_" to avoid confusion with path separator - _ => $@"\\SHELL\{string.Join("\\", folderItem.PIDL.Select(x => x.GetBytes()).Select(x => Convert.ToBase64String(x, 0, x.Length).Replace('/', '_')))}" - }; - } - - var fileName = folderItem.Properties.TryGetProperty("System.ItemNameDisplay"); - fileName ??= Path.GetFileName(folderItem.Name); // Original file name - fileName ??= folderItem.GetDisplayName(SIGDN.SIGDN_PARENTRELATIVEPARSING); - - var itemNameOrOriginalPath = folderItem.Name ?? fileName; - - // In recycle bin "Name" contains original file path + name - string filePath = Path.IsPathRooted(itemNameOrOriginalPath) ? - itemNameOrOriginalPath : parsingPath; - - if (!isFolder && !string.IsNullOrEmpty(parsingPath) && Path.GetExtension(parsingPath) is string realExtension && !string.IsNullOrEmpty(realExtension)) - { - if (!string.IsNullOrEmpty(fileName) && !fileName.EndsWith(realExtension, StringComparison.OrdinalIgnoreCase)) - fileName = $"{fileName}{realExtension}"; - - if (!string.IsNullOrEmpty(filePath) && !filePath.EndsWith(realExtension, StringComparison.OrdinalIgnoreCase)) - filePath = $"{filePath}{realExtension}"; - } - - var fileTime = folderItem.Properties.TryGetProperty("System.Recycle.DateDeleted"); - - var recycleDate = fileTime is { } deleted ? ToDateTime(deleted).ToLocalTime() : DateTime.Now; // This is LocalTime - fileTime = folderItem.Properties.TryGetProperty("System.DateModified"); - - var modifiedDate = fileTime is { } modified ? ToDateTime(modified).ToLocalTime() : SafetyExtensions.IgnoreExceptions(() => folderItem.FileInfo?.LastWriteTime) ?? DateTime.Now; // This is LocalTime - fileTime = folderItem.Properties.TryGetProperty("System.DateCreated"); - - var createdDate = fileTime is { } created ? ToDateTime(created).ToLocalTime() : SafetyExtensions.IgnoreExceptions(() => folderItem.FileInfo?.CreationTime) ?? DateTime.Now; // This is LocalTime - var fileSizeBytes = folderItem.Properties.TryGetProperty("System.Size"); - string? fileSize = fileSizeBytes is not null ? folderItem.Properties.GetPropertyString("System.Size") : null; - var fileType = folderItem.Properties.TryGetProperty("System.ItemTypeText"); - - return new(isFolder, parsingPath, fileName, filePath, recycleDate, modifiedDate, createdDate, fileSize, fileSizeBytes ?? 0, fileType, folderItem.PIDL.GetBytes()); - } - - public static ShellLinkItem? GetShellLinkItem(ShellLink? linkItem) - { - if (linkItem is null) - return null; - - var baseItem = GetShellFileItem(linkItem); - if (baseItem is null) - return null; - - string targetPath = Environment.ExpandEnvironmentVariables(linkItem.TargetPath); - var link = new ShellLinkItem(baseItem) - { - // The attributes persisted in the link file avoid opening the target, - // which can block on unreachable network locations - IsFolder = linkItem.StoredTargetIsFolder() ?? linkItem.IsTargetFolder(targetPath), - RunAsAdmin = linkItem.RunAsAdministrator, - ShowWindowCommand = (Files.App.Data.Enums.ShowWindowCommand)linkItem.ShowState, - Arguments = linkItem.Arguments, - WorkingDirectory = Environment.ExpandEnvironmentVariables(linkItem.WorkingDirectory), - TargetPath = targetPath - }; - - return link; - } - - public static string? GetParsingPath(this ShellItem? item) - { - if (item is null) - return null; - - return item.IsFileSystem ? item.FileSystemPath : item.ParsingName; - } - - public static bool GetStringAsPIDL(string pathOrPIDL, out ShellPidl? pPIDL) - { - if (pathOrPIDL.StartsWith(@"\\SHELL\", StringComparison.Ordinal)) - { - var segments = pathOrPIDL.Replace(@"\\SHELL\", "", StringComparison.Ordinal) - // Avoid confusion with path separator - .Replace('_', '/') - .Split('\\', StringSplitOptions.RemoveEmptyEntries) - .Select(Convert.FromBase64String); - pPIDL = ShellPidl.FromSegments(segments); - - return true; - } - else - { - pPIDL = null; - - return false; - } - } - - public static ShellItem GetShellItemFromPathOrPIDL(string pathOrPIDL) - { - return GetStringAsPIDL(pathOrPIDL, out var pPIDL) ? ShellItem.Open(pPIDL!) : ShellItem.Open(pathOrPIDL); - } - - private static DateTime ToDateTime(FILETIME value) - => DateTime.FromFileTimeUtc(((long)value.dwHighDateTime << 32) | (uint)value.dwLowDateTime); - - } -} diff --git a/src/Files.App/Utils/Shell/ShellHelpers.cs b/src/Files.App/Utils/Shell/ShellHelpers.cs index 3a2c6d663b9e..24283305a87f 100644 --- a/src/Files.App/Utils/Shell/ShellHelpers.cs +++ b/src/Files.App/Utils/Shell/ShellHelpers.cs @@ -9,46 +9,12 @@ public static class ShellHelpers { public static string ResolveShellPath(string shPath) { -#if WINDOWS - if (!ShellStorageFolder.IsShellPath(shPath)) - return shPath; - - shPath = Constants.UserEnvironmentPaths.ShellPlaces.GetValueOrDefault( - GetShellPathLookupKey(shPath), - shPath); - - if (shPath.StartsWith(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - return Constants.UserEnvironmentPaths.RecycleBinPath; - - if (shPath.StartsWith(Constants.UserEnvironmentPaths.MyComputerPath, StringComparison.OrdinalIgnoreCase)) - return Constants.UserEnvironmentPaths.MyComputerPath; - - if (shPath.StartsWith(Constants.UserEnvironmentPaths.NetworkFolderPath, StringComparison.OrdinalIgnoreCase)) - return Constants.UserEnvironmentPaths.NetworkFolderPath; - return shPath; -#else - return shPath; -#endif } public static bool IsSupportedShellPath(string shPath) { -#if WINDOWS - return ShellStorageFolder.IsShellPath(shPath) && - Constants.UserEnvironmentPaths.ShellPlaces.ContainsKey(GetShellPathLookupKey(shPath)); -#else return false; -#endif - } - - private static string GetShellPathLookupKey(string shPath) - { - var lookupPath = shPath.StartsWith("shell:::", StringComparison.OrdinalIgnoreCase) - ? shPath.Substring("shell:".Length) - : shPath; - - return lookupPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToUpperInvariant(); } public static string GetShellNameFromPath(string shPath) diff --git a/src/Files.App/Utils/Shell/ShellItem.cs b/src/Files.App/Utils/Shell/ShellItem.cs deleted file mode 100644 index 1a9e87c7ed11..000000000000 --- a/src/Files.App/Utils/Shell/ShellItem.cs +++ /dev/null @@ -1,723 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Collections; -using System.IO; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.System.Com; -using Windows.Win32.System.Com.StructuredStorage; -using Windows.Win32.System.SystemServices; -using Windows.Win32.System.Variant; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.Shell.Common; -using Windows.Win32.UI.Shell.PropertiesSystem; -using Windows.Win32.UI.WindowsAndMessaging; -using Win32ShellLink = Windows.Win32.UI.Shell.ShellLink; - -namespace Files.App.Utils.Shell -{ - public readonly record struct IconLocation(string Path, int Index) - { - public override string ToString() - => $"{Path},{Index}"; - } - - [WinRT.GeneratedWinRTExposedType] - public sealed partial class ShellPidl : IEnumerable - { - private readonly byte[] bytes; - - public ShellPidl(byte[] bytes) - { - ArgumentNullException.ThrowIfNull(bytes); - this.bytes = EnsureTerminated(bytes); - } - - public byte[] GetBytes() - => bytes.ToArray(); - - public unsafe bool IsParentOf(ShellPidl child, bool immediate) - { - fixed (byte* parentPidl = bytes) - fixed (byte* childPidl = child.bytes) - return PInvoke.ILIsParent((ITEMIDLIST*)parentPidl, (ITEMIDLIST*)childPidl, immediate); - } - - public static ShellPidl Combine(ShellPidl parent, ShellPidl child) - { - int parentLength = Math.Max(0, parent.bytes.Length - sizeof(ushort)); - byte[] combined = new byte[parentLength + child.bytes.Length]; - parent.bytes.AsSpan(0, parentLength).CopyTo(combined); - child.bytes.CopyTo(combined, parentLength); - return new(combined); - } - - public static ShellPidl FromSegments(IEnumerable segments) - { - using var enumerator = segments.GetEnumerator(); - if (!enumerator.MoveNext()) - throw new ArgumentException("The PIDL has no segments.", nameof(segments)); - - ShellPidl result = new(enumerator.Current); - while (enumerator.MoveNext()) - result = Combine(result, new(enumerator.Current)); - - return result; - } - - public IEnumerator GetEnumerator() - { - int offset = 0; - while (offset + sizeof(ushort) <= bytes.Length) - { - ushort segmentLength = BitConverter.ToUInt16(bytes, offset); - if (segmentLength is 0 || offset + segmentLength > bytes.Length) - yield break; - - byte[] segment = new byte[segmentLength + sizeof(ushort)]; - bytes.AsSpan(offset, segmentLength).CopyTo(segment); - yield return new(segment); - offset += segmentLength; - } - } - - IEnumerator IEnumerable.GetEnumerator() - => GetEnumerator(); - - public override bool Equals(object? obj) - => obj is ShellPidl other && bytes.AsSpan().SequenceEqual(other.bytes); - - public override int GetHashCode() - { - HashCode hash = new(); - foreach (byte value in bytes) - hash.Add(value); - return hash.ToHashCode(); - } - - private static byte[] EnsureTerminated(byte[] value) - { - if (value.Length >= sizeof(ushort) && value[^1] is 0 && value[^2] is 0) - return value.ToArray(); - - byte[] terminated = new byte[value.Length + sizeof(ushort)]; - value.CopyTo(terminated, 0); - return terminated; - } - } - - public unsafe partial class ShellItem : IDisposable - { - private IShellItem? shellItem; - private ShellItemPropertyStore? properties; - private ShellPidl? pidl; - - public ShellItem(string path) - { - HRESULT result = PInvoke.SHCreateItemFromParsingName(path, null, out IShellItem item); - result.ThrowOnFailure(); - shellItem = item; - } - - public ShellItem(Guid knownFolderId) - { - HRESULT result = PInvoke.SHGetKnownFolderItem(knownFolderId, KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, null, out IShellItem item); - result.ThrowOnFailure(); - shellItem = item; - } - - protected ShellItem(IShellItem shellItem) - { - Initialize(shellItem); - } - - protected ShellItem() - { - } - - protected void Initialize(IShellItem item) - { - shellItem = item; - properties = null; - pidl = null; - } - - public IShellItem IShellItem - => shellItem ?? throw new ObjectDisposedException(nameof(ShellItem)); - - public bool IsFolder - => HasAttribute(SFGAO_FLAGS.SFGAO_FOLDER); - - public bool IsFileSystem - => HasAttribute(SFGAO_FLAGS.SFGAO_FILESYSTEM); - - public bool IsStream - => HasAttribute(SFGAO_FLAGS.SFGAO_STREAM); - - public string? FileSystemPath - => GetDisplayName(SIGDN.SIGDN_FILESYSPATH); - - public string? ParsingName - => GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING); - - public virtual string? Name - => GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY); - - public ShellItem? Parent - { - get - { - HRESULT result = IShellItem.GetParent(out IShellItem parent); - return result.Succeeded ? Open(parent) : null; - } - } - - public ShellPidl PIDL - => pidl ??= GetPidl(); - - public ShellItemPropertyStore Properties - => properties ??= new(IShellItem); - - public FileSystemInfo? FileInfo - { - get - { - string? path = FileSystemPath; - return string.IsNullOrEmpty(path) ? null : IsFolder ? new DirectoryInfo(path) : new FileInfo(path); - } - } - - public string? GetDisplayName(SIGDN displayString) - { - HRESULT result = IShellItem.GetDisplayName(displayString, out PWSTR value); - if (result.Failed) - return null; - - try - { - return value.ToString(); - } - finally - { - PInvoke.CoTaskMemFree(value); - } - } - - public static ShellItem Open(string path) - { - var item = new ShellItem(path); - return CreateSpecializedItem(item); - } - - public static ShellItem Open(IShellItem item) - { - var shellItem = new ShellItem(item); - return CreateSpecializedItem(shellItem); - } - - public unsafe static ShellItem Open(ShellPidl pidl) - { - byte[] bytes = pidl.GetBytes(); - fixed (byte* value = bytes) - { - HRESULT result = PInvoke.SHCreateItemFromIDList(in *(ITEMIDLIST*)value, out IShellItem item); - result.ThrowOnFailure(); - return Open(item); - } - } - - public virtual void Dispose() - { - properties = null; - pidl = null; - shellItem = null; - GC.SuppressFinalize(this); - } - - private bool HasAttribute(SFGAO_FLAGS attribute) - => IShellItem.GetAttributes(attribute, out SFGAO_FLAGS returned).Succeeded && (returned & attribute) is not 0; - - private unsafe ShellPidl GetPidl() - { - HRESULT result = PInvoke.SHGetIDListFromObject(IShellItem, out ITEMIDLIST* value); - result.ThrowOnFailure(); - - try - { - uint size = PInvoke.ILGetSize(value); - byte[] bytes = new byte[size]; - Marshal.Copy((nint)value, bytes, 0, bytes.Length); - return new(bytes); - } - finally - { - PInvoke.CoTaskMemFree(value); - } - } - - private static ShellLink? TryOpenLink(ShellItem item) - { - string? path = item.FileSystemPath; - if (!string.Equals(Path.GetExtension(path), ".lnk", StringComparison.OrdinalIgnoreCase)) - return null; - - try - { - var link = new ShellLink(path!); - item.Dispose(); - return link; - } - catch - { - return null; - } - } - - private static ShellItem CreateSpecializedItem(ShellItem item) - { - if (TryOpenLink(item) is { } link) - return link; - - if (!item.IsFolder) - return item; - - var folder = new ShellFolder(item); - item.Dispose(); - return folder; - } - } - - [WinRT.GeneratedWinRTExposedType] - public partial class ShellFolder : ShellItem, IEnumerable - { - public ShellFolder(string path) : base(path) - { - } - - public ShellFolder(Guid knownFolderId) : base(knownFolderId) - { - } - - public ShellFolder(ShellItem item) : base(item.IShellItem) - { - } - - internal ShellFolder(IShellItem item) : base(item) - { - } - - public IEnumerator GetEnumerator() - { - HRESULT result = IShellItem.BindToHandler(null!, PInvoke.BHID_EnumItems, out IEnumShellItems? enumerator); - if (result.Failed || enumerator is null) - yield break; - - try - { - IShellItem[] items = new IShellItem[1]; - while (enumerator.Next(items) == HRESULT.S_OK) - yield return Open(items[0]); - } - finally - { - if ((object)enumerator is ComObject comObject) - comObject.FinalRelease(); - } - } - - IEnumerator IEnumerable.GetEnumerator() - => GetEnumerator(); - } - - public sealed partial class ShellLink : ShellItem - { - private IShellLinkW? link; - private IPersistFile? persistFile; - private string? persistedPath; - - public ShellLink(string linkPath, SLR_FLAGS resolution = SLR_FLAGS.SLR_NO_UI, HWND window = default, TimeSpan timeout = default, bool resolve = true) : base(linkPath) - { - link = Win32ShellLink.CreateInstance(); - persistFile = (IPersistFile)link; - persistFile.Load(linkPath, STGM.STGM_READ).ThrowOnFailure(); - persistedPath = linkPath; - - if (!resolve) - return; - - uint resolveFlags = (uint)resolution; - if ((resolveFlags & (uint)SLR_FLAGS.SLR_NO_UI) is not 0 && timeout != default) - { - ushort timeoutMilliseconds = checked((ushort)timeout.TotalMilliseconds); - resolveFlags = (resolveFlags & ushort.MaxValue) | ((uint)timeoutMilliseconds << 16); - } - // App-target shortcuts (shell:appsfolder) have no filesystem path, so a failed resolve must not throw - _ = link.Resolve(window, resolveFlags); - } - - public ShellLink(string targetPath, string? arguments, string? workingDirectory) - { - link = Win32ShellLink.CreateInstance(); - persistFile = (IPersistFile)link; - link.SetPath(targetPath).ThrowOnFailure(); - link.SetArguments(arguments ?? string.Empty).ThrowOnFailure(); - link.SetWorkingDirectory(workingDirectory ?? string.Empty).ThrowOnFailure(); - } - - private IShellLinkW Link - => link ?? throw new ObjectDisposedException(nameof(ShellLink)); - - private IPersistFile PersistFile - => persistFile ?? throw new ObjectDisposedException(nameof(ShellLink)); - - public string TargetPath - { - get - { - Span path = stackalloc char[32768]; - path.Clear(); - WIN32_FIND_DATAW data = default; - if (Link.GetPath(path, ref data, (uint)SLGP_FLAGS.SLGP_RAWPATH).Succeeded) - { - string result = GetNullTerminatedString(path); - if (!string.IsNullOrEmpty(result)) - return result; - } - - using ShellItem? targetItem = TryOpenTarget(); - if (targetItem is not null) - return targetItem.ParsingName ?? string.Empty; - - return string.Empty; - } - } - - /// - /// Reads the target's directory attribute from the find data persisted inside the link file, - /// without opening the target. Returns when the link stores no attributes. - /// - internal bool? StoredTargetIsFolder() - { - Span path = stackalloc char[32768]; - path.Clear(); - WIN32_FIND_DATAW data = default; - if (Link.GetPath(path, ref data, (uint)SLGP_FLAGS.SLGP_RAWPATH).Succeeded && data.dwFileAttributes is not 0) - return (data.dwFileAttributes & (uint)FileAttributes.Directory) is not 0; - - return null; - } - - internal bool IsTargetFolder(string expandedTargetPath) - { - using ShellItem? targetItem = TryOpenTarget(); - if (targetItem is not null) - return targetItem.IsFolder; - - try - { - using var fallbackTarget = Open(expandedTargetPath); - return fallbackTarget.IsFolder; - } - catch - { - return false; - } - } - - public string Arguments - { - get => GetString(Link.GetArguments); - set - { - Link.SetArguments(value).ThrowOnFailure(); - SaveCurrent(); - } - } - - public string WorkingDirectory - { - get => GetString(Link.GetWorkingDirectory); - set - { - Link.SetWorkingDirectory(value).ThrowOnFailure(); - SaveCurrent(); - } - } - - public SHOW_WINDOW_CMD ShowState - { - get - { - Link.GetShowCmd(out SHOW_WINDOW_CMD value).ThrowOnFailure(); - return value; - } - set - { - Link.SetShowCmd(value).ThrowOnFailure(); - SaveCurrent(); - } - } - - public bool RunAsAdministrator - { - get - { - IShellLinkDataList dataList = (IShellLinkDataList)Link; - dataList.GetFlags(out uint value).ThrowOnFailure(); - return (value & (uint)SHELL_LINK_DATA_FLAGS.SLDF_RUNAS_USER) is not 0; - } - set - { - IShellLinkDataList dataList = (IShellLinkDataList)Link; - dataList.GetFlags(out uint flags).ThrowOnFailure(); - flags = value - ? flags | (uint)SHELL_LINK_DATA_FLAGS.SLDF_RUNAS_USER - : flags & ~(uint)SHELL_LINK_DATA_FLAGS.SLDF_RUNAS_USER; - dataList.SetFlags(flags).ThrowOnFailure(); - SaveCurrent(); - } - } - - public IconLocation IconLocation - { - get - { - Span path = stackalloc char[32768]; - path.Clear(); - Link.GetIconLocation(path, out int index).ThrowOnFailure(); - return new(GetNullTerminatedString(path), index); - } - set - { - Link.SetIconLocation(value.Path, value.Index).ThrowOnFailure(); - SaveCurrent(); - } - } - - public void SaveAs(string path) - { - PersistFile.Save(path, true).ThrowOnFailure(); - PInvoke.SHCreateItemFromParsingName(path, null, out IShellItem item).ThrowOnFailure(); - Initialize(item); - persistedPath = path; - } - - public override void Dispose() - { - link = null; - persistFile = null; - base.Dispose(); - } - - private delegate HRESULT GetStringDelegate(Span value); - - private static string GetString(GetStringDelegate getter) - { - Span value = stackalloc char[32768]; - value.Clear(); - getter(value).ThrowOnFailure(); - return GetNullTerminatedString(value); - } - - private static string GetNullTerminatedString(Span value) - { - int length = value.IndexOf('\0'); - return value[..(length < 0 ? value.Length : length)].ToString(); - } - - private unsafe ShellItem? TryOpenTarget() - { - if (Link.GetIDList(out ITEMIDLIST* targetPidl).Failed || targetPidl is null) - return null; - - try - { - return PInvoke.SHCreateItemFromIDList(in *targetPidl, out IShellItem target).Succeeded ? Open(target) : null; - } - finally - { - PInvoke.CoTaskMemFree(targetPidl); - } - } - - private void SaveCurrent() - { - if (persistedPath is not null) - PersistFile.Save(persistedPath, true).ThrowOnFailure(); - } - } - - public sealed unsafe class ShellItemPropertyStore - { - private readonly IShellItem2? shellItem; - - public ShellItemPropertyStore(IShellItem shellItem) - { - this.shellItem = shellItem as IShellItem2; - } - - public object? this[string propertyName] - { - get - { - if (shellItem is null || PInvoke.PSGetPropertyKeyFromName(propertyName, out PROPERTYKEY key).Failed) - return null; - - return GetValue(key); - } - } - - public bool TryGetValue(PROPERTYKEY key, out T? value) - { - value = default; - if (shellItem is null) - return false; - - object? result; - if (typeof(T) == typeof(string)) - { - if (shellItem.GetString(key, out PWSTR text).Failed) - return false; - try - { - result = text.ToString(); - } - finally - { - PInvoke.CoTaskMemFree(text); - } - } - else if (typeof(T) == typeof(bool)) - { - if (shellItem.GetBool(key, out BOOL boolean).Failed) - return false; - result = (bool)boolean; - } - else if (typeof(T) == typeof(uint)) - { - if (shellItem.GetUInt32(key, out uint number).Failed) - return false; - result = number; - } - else if (typeof(T) == typeof(ulong) || typeof(T) == typeof(ulong?)) - { - if (shellItem.GetUInt64(key, out ulong number).Failed) - return false; - result = number; - } - else if (typeof(T) == typeof(System.Runtime.InteropServices.ComTypes.FILETIME) || typeof(T) == typeof(System.Runtime.InteropServices.ComTypes.FILETIME?)) - { - if (shellItem.GetFileTime(key, out System.Runtime.InteropServices.ComTypes.FILETIME fileTime).Failed) - return false; - result = fileTime; - } - else - { - result = GetValue(key); - if (result is not T) - return false; - } - - value = (T?)result; - return true; - } - - public bool TryGetValue(string propertyName, out T? value) - { - if (PInvoke.PSGetPropertyKeyFromName(propertyName, out PROPERTYKEY key).Failed) - { - value = default; - return false; - } - - return TryGetValue(key, out value); - } - - public string? GetPropertyString(PROPERTYKEY key) - { - if (shellItem is null || shellItem.GetProperty(key, out PROPVARIANT value).Failed) - return null; - - try - { - if (PInvoke.PSFormatForDisplayAlloc(key, value, PROPDESC_FORMAT_FLAGS.PDFF_DEFAULT, out PWSTR display).Failed) - return null; - try - { - return display.ToString(); - } - finally - { - PInvoke.CoTaskMemFree(display); - } - } - finally - { - PInvoke.PropVariantClear(ref value); - } - } - - public string? GetPropertyString(string propertyName) - => PInvoke.PSGetPropertyKeyFromName(propertyName, out PROPERTYKEY key).Succeeded ? GetPropertyString(key) : null; - - private object? GetValue(PROPERTYKEY key) - { - if (shellItem is null || shellItem.GetProperty(key, out PROPVARIANT value).Failed) - return null; - - try - { - return value.vt switch - { - VARENUM.VT_LPWSTR => value.pwszVal.ToString(), - VARENUM.VT_BSTR => value.bstrVal.ToString(), - VARENUM.VT_BOOL => value.boolVal.Value is not 0, - VARENUM.VT_UI4 => value.ulVal, - VARENUM.VT_UI8 => value.uhVal, - VARENUM.VT_I4 => value.lVal, - VARENUM.VT_FILETIME => value.filetime, - _ => null, - }; - } - finally - { - PInvoke.PropVariantClear(ref value); - } - } - } - - public static unsafe class InternetShortcut - { - public static string Load(string path) - { - IUniformResourceLocatorW shortcut = Create(); - ((IPersistFile)shortcut).Load(path, STGM.STGM_READ).ThrowOnFailure(); - shortcut.GetURL(out PWSTR value).ThrowOnFailure(); - try - { - return value.ToString(); - } - finally - { - PInvoke.CoTaskMemFree(value); - } - } - - public static void Save(string path, string target) - { - IUniformResourceLocatorW shortcut = Create(); - shortcut.SetURL(target, (uint)IURL_SETURL_FLAGS.IURL_SETURL_FL_GUESS_PROTOCOL).ThrowOnFailure(); - ((IPersistFile)shortcut).Save(path, false).ThrowOnFailure(); - } - - private static IUniformResourceLocatorW Create() - { - PInvoke.CoCreateInstance(PInvoke.CLSID_InternetShortcut, null, CLSCTX.CLSCTX_INPROC_SERVER, out IUniformResourceLocatorW? shortcut).ThrowOnFailure(); - return shortcut!; - } - } -} diff --git a/src/Files.App/Utils/Shell/ShellLibraryEx.cs b/src/Files.App/Utils/Shell/ShellLibraryEx.cs deleted file mode 100644 index 937165350b2f..000000000000 --- a/src/Files.App/Utils/Shell/ShellLibraryEx.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Win32; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - /// - /// Represents a Windows Shell library backed by source-generated COM interop. - /// - [WinRT.GeneratedWinRTExposedType] - public sealed partial class ShellLibraryEx : ShellFolder - { - private IShellLibrary? library; - private ShellLibraryFolders? folders; - - /// Initializes a library from its Shell item. - /// The Shell item for the library definition file. - /// Whether to open the library read-only. - public ShellLibraryEx(IShellItem libraryItem, bool readOnly = false) : this(Load(libraryItem, readOnly)) - { - } - - /// Creates a library in a known folder. - /// The library name. - /// The known folder in which to save the library. - /// Whether to overwrite an existing library with the same name. - public ShellLibraryEx(string libraryName, Guid knownFolderId, bool overwrite = false) : this(Create(libraryName, knownFolderId, overwrite)) - { - } - - private ShellLibraryEx((IShellLibrary Library, IShellItem Item) state) : base(state.Item) - { - library = state.Library; - } - - private IShellLibrary Library => library ?? throw new ObjectDisposedException(nameof(ShellLibraryEx)); - - /// Gets or sets the default target folder used for save operations. - public ShellItem DefaultSaveFolder - { - get - { - Library.GetDefaultSaveFolder(DEFAULTSAVEFOLDERTYPE.DSFT_DETECT, out IShellItem item).ThrowOnFailure(); - return Open(item); - } - set => Library.SetDefaultSaveFolder(DEFAULTSAVEFOLDERTYPE.DSFT_DETECT, value.IShellItem).ThrowOnFailure(); - } - - /// Gets the child folders contained in the library. - public ShellLibraryFolders Folders => folders ??= GetFolders(); - - /// Gets or sets whether the library is pinned to the navigation pane. - public bool PinnedToNavigationPane - { - get - { - Library.GetOptions(out LIBRARYOPTIONFLAGS options).ThrowOnFailure(); - return (options & LIBRARYOPTIONFLAGS.LOF_PINNEDTONAVPANE) is not 0; - } - set => Library.SetOptions(LIBRARYOPTIONFLAGS.LOF_PINNEDTONAVPANE, value ? LIBRARYOPTIONFLAGS.LOF_PINNEDTONAVPANE : LIBRARYOPTIONFLAGS.LOF_DEFAULT).ThrowOnFailure(); - } - - /// Reloads the library folder collection. - public void Reload() - { - folders?.Dispose(); - folders = GetFolders(); - } - - /// Commits library updates. - public void Commit() => Library.Commit().ThrowOnFailure(); - - /// - public override void Dispose() - { - folders?.Dispose(); - folders = null; - library = null; - base.Dispose(); - } - - private ShellLibraryFolders GetFolders() - { - Library.GetFolders(LIBRARYFOLDERFILTER.LFF_ALLITEMS, out IShellItemArray itemArray).ThrowOnFailure(); - return new(Library, itemArray); - } - - private static (IShellLibrary Library, IShellItem Item) Load(IShellItem item, bool readOnly) - { - IShellLibrary library = Windows.Win32.UI.Shell.ShellLibrary.CreateInstance(); - library.LoadLibraryFromItem(item, (uint)(readOnly ? STGM.STGM_READ : STGM.STGM_READWRITE)).ThrowOnFailure(); - return (library, item); - } - - private static (IShellLibrary Library, IShellItem Item) Create(string name, Guid knownFolderId, bool overwrite) - { - IShellLibrary library = Windows.Win32.UI.Shell.ShellLibrary.CreateInstance(); - library.SaveInKnownFolder(knownFolderId, name, overwrite ? LIBRARYSAVEFLAGS.LSF_OVERRIDEEXISTING : LIBRARYSAVEFLAGS.LSF_FAILIFTHERE, out IShellItem item).ThrowOnFailure(); - return (library, item); - } - } -} diff --git a/src/Files.App/Utils/Shell/ShellLibraryFolders.cs b/src/Files.App/Utils/Shell/ShellLibraryFolders.cs deleted file mode 100644 index 68e487c8fc9c..000000000000 --- a/src/Files.App/Utils/Shell/ShellLibraryFolders.cs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Collections; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Shell -{ - /// Represents the child folders contained in a Shell library. - [WinRT.GeneratedWinRTExposedType] - public sealed partial class ShellLibraryFolders : ICollection, IDisposable - { - private IShellLibrary? library; - private readonly List items = []; - - internal ShellLibraryFolders(IShellLibrary library, IShellItemArray itemArray) - { - this.library = library; - itemArray.GetCount(out uint count).ThrowOnFailure(); - for (uint index = 0; index < count; index++) - { - itemArray.GetItemAt(index, out IShellItem item).ThrowOnFailure(); - items.Add(ShellItem.Open(item)); - } - } - - private IShellLibrary Library => library ?? throw new ObjectDisposedException(nameof(ShellLibraryFolders)); - - /// - public int Count => items.Count; - - /// - public bool IsReadOnly => false; - - /// Adds a folder to the library. - public void Add(ShellItem item) - { - ArgumentNullException.ThrowIfNull(item); - Library.AddFolder(item.IShellItem).ThrowOnFailure(); - items.Add(ShellItem.Open(item.IShellItem)); - } - - /// Removes a folder from the library. - public bool Remove(ShellItem item) - { - ArgumentNullException.ThrowIfNull(item); - if (Library.RemoveFolder(item.IShellItem).Failed) - return false; - - int index = items.FindIndex(existing => ReferenceEquals(existing, item) || - existing.IShellItem.Compare(item.IShellItem, (uint)_SICHINTF.SICHINT_CANONICAL, out int order).Succeeded && order is 0); - if (index >= 0) - { - ShellItem cachedItem = items[index]; - items.RemoveAt(index); - // Dispose only the cached wrapper; the caller owns the supplied item. - if (!ReferenceEquals(cachedItem, item)) - cachedItem.Dispose(); - } - - return true; - } - - public bool Contains(ShellItem item) => items.Contains(item); - - public void CopyTo(ShellItem[] array, int arrayIndex) => items.CopyTo(array, arrayIndex); - - public IEnumerator GetEnumerator() => items.GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - void ICollection.Clear() => throw new NotSupportedException(); - - /// - public void Dispose() - { - foreach (ShellItem item in items) - item.Dispose(); - items.Clear(); - library = null; - } - } -} diff --git a/src/Files.App/Utils/Shell/ShellNewMenuHelper.cs b/src/Files.App/Utils/Shell/ShellNewMenuHelper.cs deleted file mode 100644 index f67e9c97c7e2..000000000000 --- a/src/Files.App/Utils/Shell/ShellNewMenuHelper.cs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; -using System.IO; -using System.Security; -using System.Text; -using Windows.Storage; - -namespace Files.App.Utils.Shell -{ - /// - /// Provides static helper to get extension-specific shell context menu from Windows Registry. - /// - public static class ShellNewMenuHelper - { - public static async Task> GetNewContextMenuEntries() - { - var newMenuItems = new List(); - - var shortcutExtensions = new string[] { ShellLibraryItem.EXTENSION, ".url", ".lnk" }; - - foreach (var keyName in Registry.ClassesRoot.GetSubKeyNames().Where(x => x.StartsWith('.') && !shortcutExtensions.Contains(x, StringComparer.OrdinalIgnoreCase))) - { - using var key = Registry.ClassesRoot.OpenSubKeySafe(keyName); - - if (key is not null) - { - var ret = await GetShellNewRegistryEntries(key, key); - if (ret is not null) - newMenuItems.Add(ret); - } - } - - if (!newMenuItems.Any(x => ".txt".Equals(x.Extension, StringComparison.OrdinalIgnoreCase))) - newMenuItems.Add(await CreateShellNewEntry(".txt", null, null, null)); - - return [.. newMenuItems.OrderBy(item => item.Name)]; - } - - public static async Task GetNewContextMenuEntryForType(string extension) - { - if (string.IsNullOrEmpty(extension)) - return null; - - using var key = Registry.ClassesRoot.OpenSubKeySafe(extension); - - return key is not null ? await GetShellNewRegistryEntries(key, key) : null; - } - - private static async Task GetShellNewRegistryEntries(RegistryKey current, RegistryKey root) - { - try - { - foreach (var keyName in current.GetSubKeyNames()) - { - using var key = current.OpenSubKeySafe(keyName); - - if (key is null) - continue; - - if (keyName == "ShellNew") - return await ParseShellNewRegistryEntry(key, root); - else - { - var ret = await GetShellNewRegistryEntries(key, root); - if (ret is not null) - return ret; - } - } - } - catch - { - // Ignore exceptions when the registry is inaccessible to avoid freezes - } - - return null; - } - - private static async Task ParseShellNewRegistryEntry(RegistryKey key, RegistryKey root) - { - var valueNames = key.GetValueNames(); - - if (!valueNames.Contains("NullFile", StringComparer.OrdinalIgnoreCase) && - !valueNames.Contains("Name", StringComparer.OrdinalIgnoreCase) && - !valueNames.Contains("FileName", StringComparer.OrdinalIgnoreCase) && - !valueNames.Contains("Command", StringComparer.OrdinalIgnoreCase) && - !valueNames.Contains("ItemName", StringComparer.OrdinalIgnoreCase) && - !valueNames.Contains("Data", StringComparer.OrdinalIgnoreCase)) - { - return null; - } - - var extension = root.Name.Substring(root.Name.LastIndexOf('\\') + 1); - var fileName = key.GetValue("FileName") as string; - var command = key.GetValue("Command") as string; - - byte[]? data = null; - var dataObj = key.GetValue("Data"); - - if (dataObj is not null) - { - data = key.GetValueKind("Data") switch - { - RegistryValueKind.Binary => (byte[])dataObj, - RegistryValueKind.String => Encoding.UTF8.GetBytes((string)dataObj), - _ => (byte[])dataObj, - }; - } - - return await CreateShellNewEntry(extension, fileName, command, data); - } - - private static async Task CreateShellNewEntry(string extension, string? fileName, string? command, byte[]? data) - { - var folder = await SafetyExtensions.IgnoreExceptions(() => ApplicationData.Current.LocalFolder.CreateFolderAsync("extensions", CreationCollisionOption.OpenIfExists).AsTask()); - var sampleFile = folder is not null ? await SafetyExtensions.IgnoreExceptions(() => folder.CreateFileAsync("file" + extension, CreationCollisionOption.OpenIfExists).AsTask()) : null; - - var displayType = sampleFile is not null ? sampleFile.DisplayType : $"file {extension}"; - var thumbnail = sampleFile is not null ? await SafetyExtensions.IgnoreExceptions(() => sampleFile.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.ListView, 24, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale).AsTask()) : null; - - string? iconString = null; - - if (thumbnail is not null) - { - var readStream = thumbnail.AsStreamForRead(); - var bitmapData = new byte[readStream.Length]; - await readStream.ReadExactlyAsync(bitmapData, 0, bitmapData.Length); - iconString = Convert.ToBase64String(bitmapData, 0, bitmapData.Length); - } - - var entry = new ShellNewEntry() - { - Extension = extension, - Template = fileName, - Name = displayType, - Command = command, - IconBase64 = iconString, - Data = data - }; - - return entry; - } - - private static RegistryKey? OpenSubKeySafe(this RegistryKey root, string keyName) - { - try - { - return root.OpenSubKey(keyName); - } - catch (SecurityException) - { - return null; - } - } - } -} diff --git a/src/Files.App/Utils/Shell/ShellWindowsAutomation.cs b/src/Files.App/Utils/Shell/ShellWindowsAutomation.cs deleted file mode 100644 index 4b29480d7dd5..000000000000 --- a/src/Files.App/Utils/Shell/ShellWindowsAutomation.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell.Common; - -namespace Files.App.Utils.Shell -{ - /// Provides the AOT-safe vtable calls needed for the IDispatch-based IShellWindows interface. - internal sealed unsafe partial class ShellWindowsAutomation : IDisposable - { - private const int QueryInterfaceSlot = 0; - private const int ReleaseSlot = 2; - private const int GetCountSlot = 7; - private const int GetItemSlot = 8; - private const int QueryServiceSlot = 3; - private const int BrowseObjectSlot = 11; - private const int QueryActiveShellViewSlot = 15; - private const int GetFolderSlot = 5; - private const int GetCurrentFolderSlot = 5; - - private static readonly Guid ShellWindowsClassId = new("9BA05972-F6A8-11CF-A442-00A0C90A8F39"); - private static readonly Guid ShellWindowsInterfaceId = new("85CB6900-4D95-11CF-960C-0080C7F4EE85"); - private static readonly Guid ServiceProviderInterfaceId = new("6D5140C1-7436-11CE-8034-00AA006009FA"); - private static readonly Guid TopLevelBrowserServiceId = new("4C96BE40-915C-11CF-99D3-00AA004AE837"); - private static readonly Guid ShellBrowserInterfaceId = new("000214E2-0000-0000-C000-000000000046"); - private static readonly Guid FolderViewInterfaceId = new("CDE725B0-CCC9-4519-917E-325D72FAB4CE"); - private static readonly Guid PersistFolder2InterfaceId = new("1AC3D9F0-175C-11D1-95BE-00609797EA4F"); - - private void* shellWindows; - - public ShellWindowsAutomation() - { - Guid classId = ShellWindowsClassId; - Guid interfaceId = ShellWindowsInterfaceId; - void* instance = null; - new HRESULT(CoCreateInstance(&classId, null, CLSCTX.CLSCTX_LOCAL_SERVER, &interfaceId, &instance)).ThrowOnFailure(); - if (instance is null) - throw new InvalidOperationException("The shell did not return an IShellWindows instance."); - shellWindows = instance; - } - - public int Count - { - get - { - ObjectDisposedException.ThrowIf(shellWindows is null, this); - var getCount = (delegate* unmanaged[MemberFunction])GetVtable(shellWindows)[GetCountSlot]; - int count = 0; - new HRESULT(getCount(shellWindows, &count)).ThrowOnFailure(); - return count; - } - } - - public ShellWindow? GetWindow(int index) - { - ObjectDisposedException.ThrowIf(shellWindows is null, this); - var getItem = (delegate* unmanaged[MemberFunction])GetVtable(shellWindows)[GetItemSlot]; - ComVariant itemIndex = ComVariant.Create(index); - void* window = null; - HRESULT result = new(getItem(shellWindows, itemIndex, &window)); - if (result.Failed || window is null) - { - Release(ref window); - return null; - } - - return new(window); - } - - public void Dispose() - { - Release(ref shellWindows); - GC.SuppressFinalize(this); - } - - [LibraryImport("ole32.dll", EntryPoint = "CoCreateInstance")] - [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] - private static partial int CoCreateInstance(Guid* classId, void* outer, CLSCTX context, Guid* interfaceId, void** instance); - - private static void** GetVtable(void* instance) - => *(void***)instance; - - private static HRESULT QueryInterface(void* instance, Guid interfaceId, out void* result) - { - var queryInterface = (delegate* unmanaged[MemberFunction])GetVtable(instance)[QueryInterfaceSlot]; - Guid requestedInterface = interfaceId; - void* queriedInterface = null; - HRESULT queryResult = new(queryInterface(instance, &requestedInterface, &queriedInterface)); - result = queriedInterface; - return queryResult; - } - - private static void Release(ref void* instance) - { - if (instance is null) - return; - - var release = (delegate* unmanaged[MemberFunction])GetVtable(instance)[ReleaseSlot]; - release(instance); - instance = null; - } - - internal sealed unsafe partial class ShellWindow : IDisposable - { - private void* window; - - public ShellWindow(void* window) - { - this.window = window; - } - - public bool TryNavigate(ShellPidl targetPidl, ShellPidl controlPanelPidl) - { - ObjectDisposedException.ThrowIf(window is null, this); - void* serviceProvider = null; - void* shellBrowser = null; - void* shellView = null; - void* folderView = null; - void* persistFolder = null; - ITEMIDLIST* currentFolderPidl = null; - byte[] targetBytes = targetPidl.GetBytes(); - byte[] controlPanelBytes = controlPanelPidl.GetBytes(); - - fixed (byte* target = targetBytes) - fixed (byte* controlPanel = controlPanelBytes) - { - try - { - if (QueryInterface(window, ServiceProviderInterfaceId, out serviceProvider).Failed || - serviceProvider is null) - return false; - if (QueryService(serviceProvider, TopLevelBrowserServiceId, ShellBrowserInterfaceId, out shellBrowser).Failed || - shellBrowser is null) - return false; - if (QueryActiveShellView(shellBrowser, out shellView).Failed || shellView is null) - return false; - if (QueryInterface(shellView, FolderViewInterfaceId, out folderView).Failed || folderView is null) - return false; - if (GetFolder(folderView, PersistFolder2InterfaceId, out persistFolder).Failed || - persistFolder is null) - return false; - if (GetCurrentFolder(persistFolder, out currentFolderPidl).Failed || currentFolderPidl is null) - return false; - - bool canReuse = PInvoke.ILIsParent(currentFolderPidl, (ITEMIDLIST*)target, true) || - PInvoke.ILIsEqual(currentFolderPidl, (ITEMIDLIST*)controlPanel); - return canReuse && BrowseObject(shellBrowser, (ITEMIDLIST*)target, PInvoke.SBSP_SAMEBROWSER | PInvoke.SBSP_ABSOLUTE).Succeeded; - } - finally - { - PInvoke.CoTaskMemFree(currentFolderPidl); - Release(ref persistFolder); - Release(ref folderView); - Release(ref shellView); - Release(ref shellBrowser); - Release(ref serviceProvider); - } - } - } - - public void Dispose() - { - Release(ref window); - GC.SuppressFinalize(this); - } - - private static HRESULT QueryService(void* serviceProvider, Guid serviceId, Guid interfaceId, out void* result) - { - var queryService = (delegate* unmanaged[MemberFunction])GetVtable(serviceProvider)[QueryServiceSlot]; - Guid requestedService = serviceId; - Guid requestedInterface = interfaceId; - void* service = null; - HRESULT queryResult = new(queryService(serviceProvider, &requestedService, &requestedInterface, &service)); - result = service; - return queryResult; - } - - private static HRESULT QueryActiveShellView(void* shellBrowser, out void* shellView) - { - var queryActiveShellView = (delegate* unmanaged[MemberFunction])GetVtable(shellBrowser)[QueryActiveShellViewSlot]; - void* activeView = null; - HRESULT queryResult = new(queryActiveShellView(shellBrowser, &activeView)); - shellView = activeView; - return queryResult; - } - - private static HRESULT GetFolder(void* folderView, Guid interfaceId, out void* folder) - { - var getFolder = (delegate* unmanaged[MemberFunction])GetVtable(folderView)[GetFolderSlot]; - Guid requestedInterface = interfaceId; - void* shellFolder = null; - HRESULT getFolderResult = new(getFolder(folderView, &requestedInterface, &shellFolder)); - folder = shellFolder; - return getFolderResult; - } - - private static HRESULT GetCurrentFolder(void* persistFolder, out ITEMIDLIST* folderPidl) - { - var getCurrentFolder = (delegate* unmanaged[MemberFunction])GetVtable(persistFolder)[GetCurrentFolderSlot]; - ITEMIDLIST* currentFolder = null; - HRESULT getFolderResult = new(getCurrentFolder(persistFolder, ¤tFolder)); - folderPidl = currentFolder; - return getFolderResult; - } - - private static HRESULT BrowseObject(void* shellBrowser, ITEMIDLIST* pidl, uint flags) - { - var browseObject = (delegate* unmanaged[MemberFunction])GetVtable(shellBrowser)[BrowseObjectSlot]; - return new(browseObject(shellBrowser, pidl, flags)); - } - } - } -} diff --git a/src/Files.App/Utils/Shell/ThreadWithMessageQueue.cs b/src/Files.App/Utils/Shell/ThreadWithMessageQueue.cs deleted file mode 100644 index a392cc6cf56f..000000000000 --- a/src/Files.App/Utils/Shell/ThreadWithMessageQueue.cs +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Collections.Concurrent; - -namespace Files.App.Utils.Shell -{ - public sealed partial class ThreadWithMessageQueue : Disposable - { - private readonly BlockingCollection messageQueue; - - private readonly Thread thread; - - protected override void Dispose(bool disposing) - { - if (disposing) - { - messageQueue.CompleteAdding(); - thread.Join(); - messageQueue.Dispose(); - } - } - - public Task PostMethod(Func payload) - { - var message = new Internal(payload); - messageQueue.TryAdd(message); - - return message.Task; - } - - public Task PostMethod(Action payload) - { - var message = new ActionInternal(payload); - messageQueue.TryAdd(message); - - return message.Task; - } - - public ThreadWithMessageQueue() - { - messageQueue = new BlockingCollection(new ConcurrentQueue()); - - thread = new Thread(new ThreadStart(() => - { - foreach (var message in messageQueue.GetConsumingEnumerable()) - message.Invoke(); - })); - - thread.SetApartmentState(ApartmentState.STA); - - // Do not prevent app from closing - thread.IsBackground = true; - - thread.Start(); - } - - private interface IInternal - { - void Invoke(); - } - - private sealed class Internal : IInternal - { - private readonly Func payload; - private readonly TaskCompletionSource taskCompletionSource = - new(TaskCreationOptions.RunContinuationsAsynchronously); - - public Task Task => taskCompletionSource.Task; - - public Internal(Func payload) - { - this.payload = payload; - } - - public void Invoke() - { - taskCompletionSource.SetResult(payload()); - } - } - - private sealed class ActionInternal : IInternal - { - private readonly Action payload; - private readonly TaskCompletionSource taskCompletionSource = - new(TaskCreationOptions.RunContinuationsAsynchronously); - - public Task Task => taskCompletionSource.Task; - - public ActionInternal(Action payload) - { - this.payload = payload; - } - - public void Invoke() - { - payload(); - taskCompletionSource.SetResult(); - } - } - } -} diff --git a/src/Files.App/Utils/Signatures/DigitalSignaturesUtil.cs b/src/Files.App/Utils/Signatures/DigitalSignaturesUtil.cs deleted file mode 100644 index bc09e0eedcf3..000000000000 --- a/src/Files.App/Utils/Signatures/DigitalSignaturesUtil.cs +++ /dev/null @@ -1,994 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Security.Cryptography; -using Windows.Win32.Security.WinTrust; -using static Files.App.Helpers.Win32PInvoke; - -namespace Files.App.Utils.Signatures -{ - public static class DigitalSignaturesUtil - { - // OIDs - private const string szOID_NESTED_SIGNATURE = "1.3.6.1.4.1.311.2.4.1"; - private const string szOID_RSA_counterSign = "1.2.840.113549.1.9.6"; - private const string szOID_RSA_signingTime = "1.2.840.113549.1.9.5"; - private const string szOID_RFC3161_counterSign = "1.3.6.1.4.1.311.3.3.1"; - private const string szOID_OIWSEC_sha1 = "1.3.14.3.2.26"; - private const string szOID_RSA_MD5 = "1.2.840.113549.2.5"; - private const string szOID_NIST_sha256 = "2.16.840.1.101.3.4.2.1"; - - // Flags - private const uint CERT_NAME_SIMPLE_DISPLAY_TYPE = 4; - private const uint CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000; - private const uint PKCS_7_ASN_ENCODING = 0x00010000; - private const uint CRYPT_ASN_ENCODING = 0x00000001; - private const CERT_QUERY_ENCODING_TYPE ENCODING = - CERT_QUERY_ENCODING_TYPE.X509_ASN_ENCODING | CERT_QUERY_ENCODING_TYPE.PKCS_7_ASN_ENCODING; - - private const uint CMSG_SIGNER_INFO_PARAM = 6; - - // Version numbers - private const uint CERT_V1 = 0; - private const uint CERT_V2 = 1; - private const uint CERT_V3 = 2; - - private static readonly byte[] SG_ProtoCoded = [ - 0x30, 0x82 - ]; - - private static readonly byte[] SG_SignedData = [ - 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02 - ]; - - private static readonly IDateTimeFormatter formatter = Ioc.Default.GetRequiredService(); - - public static void LoadItemSignatures( - string filePath, - ObservableCollection signatures, - HWND hWnd, - CancellationToken ct) - { - var signChain = new List(); - GetSignerCertificateInfo(filePath, signChain, ct); - - foreach (var signNode in signChain) - { - if (signNode.CertChain.Count == 0) - continue; - - var signatureInfo = new SignatureInfoItem(filePath, signNode.Index, hWnd, signNode.CertChain) - { - Version = signNode.Version, - IssuedBy = signNode.CertChain[0].IssuedBy, - IssuedTo = signNode.CertChain[0].IssuedTo, - ValidFromTimestamp = signNode.CertChain[0].ValidFrom, - ValidToTimestamp = signNode.CertChain[0].ValidTo, - VerifiedTimestamp = signNode.CounterSign.TimeStamp, - Verified = signNode.IsValid, - }; - signatures.Add(signatureInfo); - } - } - - public unsafe static void DisplaySignerInfoDialog(string filePath, HWND hwndParent, int index) - { - if (string.IsNullOrEmpty(filePath)) - return; - - void* hAuthCryptMsg = null; - var signHandle = new SignDataHandle(); - var signDataChain = new List(); - - try - { - var result = TryGetSignerInfo( - filePath, - out hAuthCryptMsg, - out signHandle.hCertStoreHandle, - out signHandle.pSignerInfo, - out signHandle.dwObjSize - ); - if (!result || signHandle.pSignerInfo is null) - return; - - signDataChain.Add(signHandle); - GetNestedSignerInfo(ref signHandle, signDataChain); - if (index >= signDataChain.Count) - return; - - signHandle = signDataChain[index]; - var issuer = signHandle.pSignerInfo->Issuer; - var pCertContext = PInvoke.CertFindCertificateInStore( - signHandle.hCertStoreHandle, - ENCODING, - 0, - CERT_FIND_FLAGS.CERT_FIND_ISSUER_NAME, - &issuer, - null - ); - if (pCertContext is null) - return; - - var viewInfo = new CRYPTUI_VIEWSIGNERINFO_STRUCT - { - dwSize = (uint)Marshal.SizeOf(), - hwndParent = hwndParent, - dwFlags = 0, - szTitle = (PCSTR)null, - pSignerInfo = signHandle.pSignerInfo, - hMsg = hAuthCryptMsg, - pszOID = (PCSTR)null, - dwReserved = null, - cStores = 1, - rghStores = (HCERTSTORE*)NativeMemory.Alloc((uint)sizeof(void*)), - cPropPages = 0, - rgPropPages = null - }; - *(viewInfo.rghStores) = signHandle.hCertStoreHandle; - - result = CryptUIDlgViewSignerInfo(&viewInfo); - - PInvoke.CertFreeCertificateContext(pCertContext); - } - finally - { - // Since signDataChain contains nested signatures, - // you must release them starting from the last one. - for (int i = signDataChain.Count - 1; i >= 0; i--) - { - if (signDataChain[i].pSignerInfo is not null) - NativeMemory.Free(signDataChain[i].pSignerInfo); - - if (!signDataChain[i].hCertStoreHandle.IsNull) - PInvoke.CertCloseStore(signDataChain[i].hCertStoreHandle, 0); - } - - if (hAuthCryptMsg is not null) - PInvoke.CryptMsgClose(hAuthCryptMsg); - } - } - - private unsafe static bool GetSignerSignatureInfo( - HCERTSTORE hSystemStore, - HCERTSTORE hCertStore, - CERT_CONTEXT* pOrigContext, - ref CERT_CONTEXT* pCurrContext, - SignNodeInfo signNode) - { - var pCertInfo = pCurrContext->pCertInfo; - var certNode = new CertNodeInfoItem(); - - (_, certNode.Version) = CalculateSignVersion(pCertInfo->dwVersion); - GetStringFromCertContext(pCurrContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, certNode); - GetStringFromCertContext(pCurrContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 1, certNode); - - var pft = &(pCertInfo->NotBefore); - certNode.ValidFrom = TimeToString(pft); - pft = &(pCertInfo->NotAfter); - certNode.ValidTo = TimeToString(pft); - - signNode.CertChain.Add(certNode); - - pCurrContext = PInvoke.CertFindCertificateInStore( - hCertStore, - ENCODING, - 0, - CERT_FIND_FLAGS.CERT_FIND_SUBJECT_NAME, - &(pCertInfo->Issuer), - null - ); - - if (pCurrContext is null) - { - pCurrContext = PInvoke.CertFindCertificateInStore( - hSystemStore, - ENCODING, - 0, - CERT_FIND_FLAGS.CERT_FIND_SUBJECT_NAME, - &(pCertInfo->Issuer), - null - ); - } - - if (pCurrContext is null) - return false; - - var result = PInvoke.CertComparePublicKeyInfo( - ENCODING, - &pCurrContext->pCertInfo->SubjectPublicKeyInfo, - &pOrigContext->pCertInfo->SubjectPublicKeyInfo - ); - - return !result; - } - - private unsafe static bool GetSignerCertificateInfo(string fileName, List signChain, CancellationToken ct) - { - var succeded = false; - var authSignData = new SignDataHandle() { dwObjSize = 0, hCertStoreHandle = HCERTSTORE.Null, pSignerInfo = null }; - var signDataChain = new List(); - signChain.Clear(); - - var cert_store_prov_system = (PCSTR)(byte*)10; - HCERTSTORE hSystemStore; - fixed (char* pRoot = "Root") - { - hSystemStore = PInvoke.CertOpenStore( - cert_store_prov_system, - ENCODING, - HCRYPTPROV_LEGACY.Null, - (CERT_OPEN_STORE_FLAGS)CERT_SYSTEM_STORE_CURRENT_USER, - (void*)pRoot - ); - } - if (hSystemStore == IntPtr.Zero) - return false; - - void* hAuthCryptMsg = null; - var result = TryGetSignerInfo( - fileName, - out hAuthCryptMsg, - out authSignData.hCertStoreHandle, - out authSignData.pSignerInfo, - out authSignData.dwObjSize - ); - - if (hAuthCryptMsg is not null) - { - PInvoke.CryptMsgClose(hAuthCryptMsg); - hAuthCryptMsg = null; - } - - if (!result) - { - if (authSignData.hCertStoreHandle != IntPtr.Zero) - PInvoke.CertCloseStore(authSignData.hCertStoreHandle, 0); - - PInvoke.CertCloseStore(hSystemStore, 0); - return false; - } - - signDataChain.Add(authSignData); - GetNestedSignerInfo(ref authSignData, signDataChain); - - for (var i = 0; i < signDataChain.Count; i++) - { - if (ct.IsCancellationRequested) - { - PInvoke.CertCloseStore(hSystemStore, 0); - return false; - } - - CERT_CONTEXT* pCurrContext = null; - CMSG_SIGNER_INFO* pCounterSigner = null; - var signNode = new SignNodeInfo(); - - GetCounterSignerInfo(signDataChain[i].pSignerInfo, &pCounterSigner); - if (pCounterSigner is not null) - GetCounterSignerData(pCounterSigner, signNode.CounterSign); - else - GetGeneralizedTimeStamp(signDataChain[i].pSignerInfo, signNode.CounterSign); - - var pszObjId = signDataChain[i].pSignerInfo->HashAlgorithm.pszObjId; - var szObjId = new string((sbyte*)(byte*)pszObjId); - CalculateDigestAlgorithm(szObjId, signNode); - (_, signNode.Version) = CalculateSignVersion(signDataChain[i].pSignerInfo->dwVersion); - - - var pIssuer = &(signDataChain[i].pSignerInfo->Issuer); - pCurrContext = PInvoke.CertFindCertificateInStore( - signDataChain[i].hCertStoreHandle, - ENCODING, - 0, - CERT_FIND_FLAGS.CERT_FIND_ISSUER_NAME, - pIssuer, - null - ); - - result = pCurrContext is not null; - while (result) - { - var pOrigContext = pCurrContext; - result = GetSignerSignatureInfo( - hSystemStore, - signDataChain[i].hCertStoreHandle, - pOrigContext, - ref pCurrContext, - signNode - ); - PInvoke.CertFreeCertificateContext(pOrigContext); - } - - if (pCurrContext is not null) - PInvoke.CertFreeCertificateContext(pCurrContext); - - if (pCounterSigner is not null) - NativeMemory.Free(pCounterSigner); - - if (signDataChain[i].pSignerInfo is not null) - NativeMemory.Free(signDataChain[i].pSignerInfo); - - if (!signDataChain[i].hCertStoreHandle.IsNull) - PInvoke.CertCloseStore(signDataChain[i].hCertStoreHandle, 0); - - succeded = true; - signNode.IsValid = VerifyySignature(fileName); - signNode.Index = i; - signChain.Add(signNode); - } - - PInvoke.CertCloseStore(hSystemStore, 0); - return succeded; - } - - private unsafe static bool VerifyySignature(string certPath) - { - int res = 1; - var sFileInfo = (uint)Marshal.SizeOf(); - var sData = (uint)Marshal.SizeOf(); - var actionGuid = new Guid("{00AAC56B-CD44-11D0-8CC2-00C04FC295EE}"); - - fixed (char* pCertPath = certPath) - { - var fileInfo = new WINTRUST_FILE_INFO - { - cbStruct = sFileInfo, - pcwszFilePath = (PCWSTR)pCertPath, - hFile = (HANDLE)null, - pgKnownSubject = null - }; - - var wintrustData = new WINTRUST_DATA - { - cbStruct = sData, - pPolicyCallbackData = null, - pSIPClientData = null, - dwUIChoice = WINTRUST_DATA_UICHOICE.WTD_UI_NONE, - fdwRevocationChecks = 0, // No revocation checking - dwUnionChoice = WINTRUST_DATA_UNION_CHOICE.WTD_CHOICE_FILE, - dwStateAction = WINTRUST_DATA_STATE_ACTION.WTD_STATEACTION_VERIFY, - hWVTStateData = (HANDLE)null, - pwszURLReference = null, - dwUIContext = 0, - Anonymous = new WINTRUST_DATA._Anonymous_e__Union - { - pFile = &fileInfo, - }, - }; - - res = PInvoke.WinVerifyTrust((HWND)null, ref actionGuid, &wintrustData); - - // Release hWVTStateData - wintrustData.dwStateAction = WINTRUST_DATA_STATE_ACTION.WTD_STATEACTION_CLOSE; - PInvoke.WinVerifyTrust((HWND)null, ref actionGuid, &wintrustData); - } - - return res == 0; - } - - private unsafe static bool TryGetSignerInfo( - string fileName, - out void* hMsg, - out HCERTSTORE hCertStore, - out CMSG_SIGNER_INFO* pSignerInfo, - out uint signerSize, - uint index = 0) - { - CERT_QUERY_ENCODING_TYPE encoding = 0; - CERT_QUERY_CONTENT_TYPE dummy = 0; - CERT_QUERY_FORMAT_TYPE dummy2 = 0; - void* pDummy = null; - BOOL result = false; - - HCERTSTORE hCertStoreTmp = HCERTSTORE.Null; - void* hMsgTmp = null; - - fixed (char* pFileName = fileName) - { - result = PInvoke.CryptQueryObject( - CERT_QUERY_OBJECT_TYPE.CERT_QUERY_OBJECT_FILE, - pFileName, - CERT_QUERY_CONTENT_TYPE_FLAGS.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, - CERT_QUERY_FORMAT_TYPE_FLAGS.CERT_QUERY_FORMAT_FLAG_BINARY, - 0, - &encoding, - &dummy, - &dummy2, - &hCertStoreTmp, - &hMsgTmp, - &pDummy - ); - } - - hCertStore = hCertStoreTmp; - hMsg = hMsgTmp; - pSignerInfo = null; - signerSize = 0; - - if (!result) - return false; - - var vpSignerInfo = (void*)pSignerInfo; - result = CustomCryptMsgGetParam( - hMsg, - CMSG_SIGNER_INFO_PARAM, - index, - ref vpSignerInfo, - ref signerSize - ); - pSignerInfo = (CMSG_SIGNER_INFO*)vpSignerInfo; - - return result; - } - - private unsafe static bool GetCounterSignerInfo( - CMSG_SIGNER_INFO* pSignerInfo, - CMSG_SIGNER_INFO** pTargetSigner) - { - uint objSize = 0; - if (pSignerInfo is null || pTargetSigner is null) - return false; - - try - { - *pTargetSigner = null; - CRYPT_ATTRIBUTE* attr = null; - var res = TryGetUnauthAttr(pSignerInfo, szOID_RSA_counterSign, ref attr); - if (!res || attr is null) - return false; - - var pkcs7_signer_info = (PCSTR)(byte*)500; - var result = PInvoke.CryptDecodeObject( - ENCODING, - pkcs7_signer_info, - attr->rgValue[0].pbData, - attr->rgValue[0].cbData, - 0, - null, - &objSize - ); - if (!result) - return false; - - *pTargetSigner = (CMSG_SIGNER_INFO*)NativeMemory.Alloc(objSize); - if (*pTargetSigner is null) - return false; - - result = PInvoke.CryptDecodeObject( - ENCODING, - pkcs7_signer_info, - attr->rgValue[0].pbData, - attr->rgValue[0].cbData, - 0, - *pTargetSigner, - &objSize - ); - if (!result) - return false; - } - finally - { - } - - return true; - } - - private unsafe static bool GetCounterSignerData(CMSG_SIGNER_INFO* pSignerInfo, SignCounterSign counterSign) - { - CRYPT_ATTRIBUTE* attr = null; - var res = TryGetAuthAttr(pSignerInfo, szOID_RSA_signingTime, ref attr); - if (!res || attr is null) - return false; - - var data = (uint)Marshal.SizeOf(); - var ft = (System.Runtime.InteropServices.ComTypes.FILETIME*)NativeMemory.Alloc(data); - try - { - var pkcs_utc_time = (PCSTR)(byte*)17; - var result = PInvoke.CryptDecodeObject( - ENCODING, - pkcs_utc_time, - attr->rgValue[0].pbData, - attr->rgValue[0].cbData, - 0, - ft, - &data - ); - if (!result) - return false; - - PInvoke.FileTimeToLocalFileTime(*ft, out var lft); - PInvoke.FileTimeToSystemTime(lft, out var st); - counterSign.TimeStamp = TimeToString(null, &st); - - return true; - } - finally - { - NativeMemory.Free(ft); - } - } - - private unsafe static bool ParseDERFindType( - int typeSearch, - byte* pbSignature, - uint size, - ref uint positionFound, - ref uint lengthFound) - { - uint position = 0; - uint sizeFound = 0; - uint bytesParsed = 0; - var iType = 0; - var iClass = 0; - positionFound = 0; - lengthFound = 0; - if (pbSignature is null) - return false; - - while (size > position) - { - if (!SafeToReadNBytes(size, position, 2)) - return false; - - ParseDERType(pbSignature[position], ref iType, ref iClass); - switch (iType) - { - case 0x05: // Null - ++position; - if (pbSignature[position] != 0x00) - return false; - - ++position; - break; - - case 0x06: // Object Identifier - ++position; - if (!SafeToReadNBytes(size - position, 1, pbSignature[position])) - return false; - - position += 1u + pbSignature[position]; - break; - - case 0x00: // ? - case 0x01: // Boolean - case 0x02: // Integer - case 0x03: // Bit String - case 0x04: // Octet String - case 0x0A: // enumerated - case 0x0C: // UTF8string - case 0x13: // printable string - case 0x14: // T61 string - case 0x16: // IA5String - case 0x17: // UTC time - case 0x18: // Generalized time - case 0x1E: // BMPstring - ++position; - if (!ParseDERSize( - pbSignature + position, - size - position, - ref sizeFound, - ref bytesParsed)) - { - return false; - } - - position += bytesParsed; - if (!SafeToReadNBytes(size - position, 0, sizeFound)) - return false; - - if (typeSearch == iType) - { - positionFound = position; - lengthFound = sizeFound; - - return true; - } - - position += sizeFound; - break; - - case 0x20: // context specific - case 0x21: // context specific - case 0x23: // context specific - case 0x24: // context specific - case 0x30: // sequence - case 0x31: // set - position++; - if (!ParseDERSize( - pbSignature + position, - size - position, - ref sizeFound, - ref bytesParsed)) - { - return false; - } - - position += bytesParsed; - break; - - case 0x22: // ? - position += 2; - break; - - default: - return false; - } - } - - return false; - } - - private unsafe static bool GetGeneralizedTimeStamp( - CMSG_SIGNER_INFO* pSignerInfo, - SignCounterSign counter) - { - uint positionFound = 0; - uint lengthFound = 0; - CRYPT_ATTRIBUTE* attr = null; - var res = TryGetUnauthAttr(pSignerInfo, szOID_RFC3161_counterSign, ref attr); - if (!res || attr is null) - return false; - - var result = ParseDERFindType( - 0x04, - attr->rgValue[0].pbData, - attr->rgValue[0].cbData, - ref positionFound, - ref lengthFound); - if (!result) - return false; - - // Counter Signer Timstamp - var pbOctetString = attr->rgValue[0].pbData + positionFound; - counter.TimeStamp = GetTimeStampFromDER(pbOctetString, lengthFound, ref positionFound); - - return true; - } - - private unsafe static string GetTimeStampFromDER(byte* pbOctetString, uint lengthFound, ref uint positionFound) - { - var result = ParseDERFindType( - 0x18, - pbOctetString, - lengthFound, - ref positionFound, - ref lengthFound - ); - if (!result) - return string.Empty; - - var st = new Windows.Win32.Foundation.SYSTEMTIME(); - var buffer = new ReadOnlySpan(pbOctetString + positionFound, (int)lengthFound); - - _ = ushort.TryParse(buffer.Slice(0, 4), out st.wYear); - _ = ushort.TryParse(buffer.Slice(4, 2), out st.wMonth); - _ = ushort.TryParse(buffer.Slice(6, 2), out st.wDay); - _ = ushort.TryParse(buffer.Slice(8, 2), out st.wHour); - _ = ushort.TryParse(buffer.Slice(10, 2), out st.wMinute); - _ = ushort.TryParse(buffer.Slice(12, 2), out st.wSecond); - - if (buffer.Length >= 18 && buffer[14] == '.') - _ = ushort.TryParse(buffer.Slice(15, 3), out st.wMilliseconds); - - PInvoke.SystemTimeToFileTime(st, out var fft); - PInvoke.FileTimeToLocalFileTime(fft, out var lft); - PInvoke.FileTimeToSystemTime(lft, out var lst); - var timestamp = TimeToString(null, &lst); - - return timestamp; - } - - private unsafe static bool GetStringFromCertContext(CERT_CONTEXT* pCertContext, uint dwType, uint flag, CertNodeInfoItem info) - { - var data = PInvoke.CertGetNameString(pCertContext, dwType, flag, null, (PWSTR)null, 0); - if (data == 0) - { - PInvoke.CertFreeCertificateContext(pCertContext); - return false; - } - - var pszTempName = (PWSTR)NativeMemory.Alloc(data * sizeof(char)); - if (pszTempName.Value is null) - { - PInvoke.CertFreeCertificateContext(pCertContext); - NativeMemory.Free(pszTempName); - return false; - } - - data = PInvoke.CertGetNameString(pCertContext, dwType, flag, null, pszTempName, data); - if (data == 0) - { - NativeMemory.Free(pszTempName); - return false; - } - - var name = pszTempName.AsSpan().ToString(); - NativeMemory.Free(pszTempName); - if (flag == 0) - info.IssuedTo = StripString(name); - else - info.IssuedBy = StripString(name); - - return true; - } - - private unsafe static bool TryGetUnauthAttr(CMSG_SIGNER_INFO* pSignerInfo, string oid, ref CRYPT_ATTRIBUTE* attr) - { - int n = 0; - attr = null; - for (; n < pSignerInfo->UnauthAttrs.cAttr; n++) - { - attr = &pSignerInfo->UnauthAttrs.rgAttr[n]; - var objId = new string((sbyte*)(byte*)attr->pszObjId); - if (objId == oid) - break; - } - - return n < pSignerInfo->UnauthAttrs.cAttr; - } - - private unsafe static bool TryGetAuthAttr(CMSG_SIGNER_INFO* pSignerInfo, string oid, ref CRYPT_ATTRIBUTE* attr) - { - int n = 0; - attr = null; - for (; n < pSignerInfo->AuthAttrs.cAttr; n++) - { - attr = &pSignerInfo->AuthAttrs.rgAttr[n]; - var objId = new string((sbyte*)(byte*)attr->pszObjId); - if (objId == oid) - break; - } - - return n < pSignerInfo->AuthAttrs.cAttr; - } - - private unsafe static bool GetNestedSignerInfo(ref SignDataHandle AuthSignData, List NestedChain) - { - var succeded = false; - void* hNestedMsg = null; - if (AuthSignData.pSignerInfo is null) - return false; - - try - { - CRYPT_ATTRIBUTE* attr = null; - var res = TryGetUnauthAttr(AuthSignData.pSignerInfo, szOID_NESTED_SIGNATURE, ref attr); - if (!res || attr is null) - return false; - - var cbCurrData = attr->rgValue[0].cbData; - var pbCurrData = attr->rgValue[0].pbData; - var upperBound = AuthSignData.pSignerInfo + AuthSignData.dwObjSize; - while (pbCurrData > AuthSignData.pSignerInfo && pbCurrData < upperBound) - { - var nestedHandle = new SignDataHandle() { dwObjSize = 0, pSignerInfo = null, hCertStoreHandle = HCERTSTORE.Null }; - if (!Memcmp(pbCurrData, SG_ProtoCoded) || - !Memcmp(pbCurrData + 6, SG_SignedData)) - { - break; - } - - hNestedMsg = PInvoke.CryptMsgOpenToDecode( - PKCS_7_ASN_ENCODING | CRYPT_ASN_ENCODING, - 0, - 0, - HCRYPTPROV_LEGACY.Null, - null, - null - ); - if (hNestedMsg is null) - return false; - - cbCurrData = XCHWordLitend(*(ushort*)(pbCurrData + 2)) + 4u; - var pbNextData = pbCurrData; - pbNextData += EightByteAlign(cbCurrData, (long)pbCurrData); - var result = PInvoke.CryptMsgUpdate(hNestedMsg, pbCurrData, cbCurrData, true); - pbCurrData = pbNextData; - if (!result) - continue; - - var pSignerInfo = (void*)nestedHandle.pSignerInfo; - result = CustomCryptMsgGetParam( - hNestedMsg, - CMSG_SIGNER_INFO_PARAM, - 0, - ref pSignerInfo, - ref nestedHandle.dwObjSize - ); - nestedHandle.pSignerInfo = (CMSG_SIGNER_INFO*)pSignerInfo; - if (!result) - continue; - - var cert_store_prov_msg = (PCSTR)(byte*)1; - nestedHandle.hCertStoreHandle = PInvoke.CertOpenStore( - cert_store_prov_msg, - ENCODING, - HCRYPTPROV_LEGACY.Null, - 0, - hNestedMsg - ); - - succeded = true; - NestedChain.Add(nestedHandle); - } - } - finally - { - if (hNestedMsg is not null) - PInvoke.CryptMsgClose(hNestedMsg); - } - - return succeded; - } - - private unsafe static bool CustomCryptMsgGetParam( - void* hCryptMsg, - uint paramType, - uint index, - ref void* pParam, - ref uint outSize) - { - bool result; - uint size = 0; - - result = PInvoke.CryptMsgGetParam( - hCryptMsg, - paramType, - index, - null, - &size - ); - if (!result) - return false; - - pParam = NativeMemory.Alloc(size); - if (pParam is null) - return false; - - result = PInvoke.CryptMsgGetParam( - hCryptMsg, - paramType, - index, - pParam, - &size - ); - if (!result) - return false; - - outSize = size; - return true; - } - - private static ushort XCHWordLitend(uint num) - => (ushort)(((((ushort)num) & 0xFF00) >> 8) | (((ushort)num) & 0x00FF) << 8); - - private static long EightByteAlign(long offset, long b) - => ((offset + b + 7) & 0xFFFFFFF8L) - (b & 0xFFFFFFF8L); - - private unsafe static bool Memcmp(byte* ptr1, byte[] arr) - { - for (var i = 0; i < arr.Length; i++) - { - if (ptr1[i] != arr[i]) - return false; - } - - return true; - } - - private static (bool, string) CalculateSignVersion(uint versionNumber) - { - var res = versionNumber switch - { - CERT_V1 => "V1", - CERT_V2 => "V2", - CERT_V3 => "V3", - _ => "Unknown", - }; - return (true, res); - } - - private static bool CalculateDigestAlgorithm(string pszObjId, SignNodeInfo info) - { - if (string.IsNullOrWhiteSpace(pszObjId)) - info.DigestAlgorithm = "Unknown"; - else if (pszObjId == szOID_OIWSEC_sha1) - info.DigestAlgorithm = "SHA1"; - else if (pszObjId == szOID_RSA_MD5) - info.DigestAlgorithm = "MD5"; - else if (pszObjId == szOID_NIST_sha256) - info.DigestAlgorithm = "SHA256"; - else - info.DigestAlgorithm = StripString(pszObjId); - - return true; - } - - private static bool SafeToReadNBytes(uint size, uint start, uint requestSize) - => size - start >= requestSize; - - private static void ParseDERType(byte bIn, ref int iType, ref int iClass) - { - iType = bIn & 0x3F; - iClass = bIn >> 6; - } - - private unsafe static uint ReadNumberFromNBytes(byte* pbSignature, uint start, uint requestSize) - { - uint number = 0; - for (var i = 0; i < requestSize; i++) - number = number * 0x100 + pbSignature[start + i]; - - return number; - } - - private unsafe static bool ParseDERSize(byte* pbSignature, uint size, ref uint sizeFound, ref uint bytesParsed) - { - if (pbSignature[0] > 0x80 && !SafeToReadNBytes(size, 1, pbSignature[0] - 0x80u)) - return false; - - if (pbSignature[0] <= 0x80) - { - sizeFound = pbSignature[0]; - bytesParsed = 1; - } - else - { - sizeFound = ReadNumberFromNBytes(pbSignature, 1, pbSignature[0] - 0x80u); - bytesParsed = pbSignature[0] - 0x80u + 1; - } - - return true; - } - - private static string StripString(string? str) - { - return str? - .Replace("\t", "")? - .Replace("\n", "")? - .Replace("\r", "")? - .Replace(((char)0).ToString(), "") ?? string.Empty; - } - - private unsafe static string TimeToString( - System.Runtime.InteropServices.ComTypes.FILETIME* pftIn, - Windows.Win32.Foundation.SYSTEMTIME* pstIn = null) - { - if (pstIn is null) - { - if (pftIn is null) - return string.Empty; - - PInvoke.FileTimeToSystemTime(*pftIn, out var sysTime); - pstIn = &sysTime; - } - - var date = new DateTime( - pstIn->wYear, pstIn->wMonth, pstIn->wDay, - pstIn->wHour, pstIn->wMinute, pstIn->wSecond - ); - - return formatter.ToLongLabel(date); - } - - class SignCounterSign - { - public string TimeStamp { get; set; } = string.Empty; - } - - class SignNodeInfo - { - public bool IsValid { get; set; } = false; - public string DigestAlgorithm { get; set; } = string.Empty; - public string Version { get; set; } = string.Empty; - public int Index { get; set; } = 0; - public SignCounterSign CounterSign { get; set; } = new(); - public List CertChain { get; set; } = []; - } - } -} diff --git a/src/Files.App/Utils/Storage/Enumerators/UniversalStorageEnumerator.Windows.cs b/src/Files.App/Utils/Storage/Enumerators/UniversalStorageEnumerator.Windows.cs deleted file mode 100644 index 22d7d28779e1..000000000000 --- a/src/Files.App/Utils/Storage/Enumerators/UniversalStorageEnumerator.Windows.cs +++ /dev/null @@ -1,374 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Services.SizeProvider; -using Files.Shared.Helpers; -using Microsoft.Extensions.Logging; -using Microsoft.UI.Xaml.Media.Imaging; -using System.IO; -using Windows.Storage; - -namespace Files.App.Utils.Storage -{ - public static class UniversalStorageEnumerator - { - private static readonly ISizeProvider folderSizeProvider = Ioc.Default.GetRequiredService(); - - private static readonly IIconCacheService iconCacheService = Ioc.Default.GetRequiredService(); - - public static async Task> ListEntries( - BaseStorageFolder rootFolder, - StorageFolderWithPath currentStorageFolder, - CancellationToken cancellationToken, - int countLimit, - uint iconSize, - Func, Task> intermediateAction, - Dictionary? defaultIconPairs = null) - { - var sampler = new IntervalSampler(500); - var tempList = new List(); - uint count = 0; - var firstRound = true; - - IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService(); - bool calculateFolderSizes = userSettingsService.FoldersSettingsService.CalculateFolderSizes; - - while (true) - { - IReadOnlyList items; - - uint maxItemsToRetrieve = 300; - - if (intermediateAction is null) - { - // without intermediate action increase batches significantly - maxItemsToRetrieve = 1000; - } - else if (firstRound) - { - // A small first fetch gets content on screen quickly; later rounds use full batches - maxItemsToRetrieve = 8; - firstRound = false; - } - - try - { - items = await rootFolder.GetItemsAsync(count, maxItemsToRetrieve); - if (items is null || items.Count == 0) - { - break; - } - } - catch (NotImplementedException) - { - break; - } - catch (OperationCanceledException) // Password dialog dismissed - let the caller handle it - { - throw; - } - catch (Exception ex) when ( - ex is UnauthorizedAccessException || - ex is FileNotFoundException || - (uint)ex.HResult == 0x80070490) // ERROR_NOT_FOUND - { - // If some unexpected exception is thrown - enumerate this folder file by file - just to be sure - items = await EnumerateFileByFile(rootFolder, count, maxItemsToRetrieve); - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Error enumerating directory contents."); - - break; - } - - foreach (var item in items) - { - var startWithDot = item.Name.StartsWith('.'); - if (!startWithDot || userSettingsService.FoldersSettingsService.ShowDotFiles) - { - if (item.IsOfType(StorageItemTypes.Folder)) - { - var folder = await AddFolderAsync(item.AsBaseStorageFolder()!, currentStorageFolder, cancellationToken); - if (folder is not null) - { - var folderPath = folder.ItemPath!; - folder.PreloadedIconData = await iconCacheService.GetIconAsync(folder.ItemPath, null, true, iconSize); - - if (defaultIconPairs?.ContainsKey(string.Empty) ?? false) - folder.FileImage = defaultIconPairs[string.Empty]; - - tempList.Add(folder); - - // The size provider enumerates with Win32, which reports size 0 for - // virtual paths (ftp, archives) it cannot traverse; skip those - if (calculateFolderSizes && FolderHelpers.CheckFolderAccessWithWin32(folderPath)) - { - if (folderSizeProvider.TryGetSize(folderPath, out var size)) - { - folder.FileSizeBytes = (long)size; - folder.FileSize = size.ToSizeString(); - } - - _ = folderSizeProvider.UpdateAsync(folderPath, cancellationToken); - } - } - } - else - { - var fileEntry = await AddFileAsync(item.AsBaseStorageFile()!, currentStorageFolder, cancellationToken); - if (fileEntry is not null) - { - fileEntry.PreloadedIconData = await iconCacheService.GetIconAsync(fileEntry.ItemPath, fileEntry.FileExtension, false, iconSize); - - if (defaultIconPairs is not null) - { - if (!string.IsNullOrEmpty(fileEntry.FileExtension)) - { - var lowercaseExtension = fileEntry.FileExtension.ToLowerInvariant(); - - if (defaultIconPairs.TryGetValue(lowercaseExtension, out BitmapImage? image)) - fileEntry.FileImage = image; - } - } - - tempList.Add(fileEntry); - } - } - } - - if (cancellationToken.IsCancellationRequested) - break; - } - - count += maxItemsToRetrieve; - - if (countLimit > -1 && count >= countLimit) - break; - - if (intermediateAction is not null && (items.Count == maxItemsToRetrieve || sampler.CheckNow())) - { - await intermediateAction(tempList); - - // clear the temporary list every time we do an intermediate action - tempList.Clear(); - } - } - - return tempList; - } - - private static async Task> EnumerateFileByFile(BaseStorageFolder rootFolder, uint startFrom, uint itemsToIterate) - { - var tempList = new List(); - - for (var i = startFrom; i < startFrom + itemsToIterate; i++) - { - IStorageItem? item; - try - { - var results = await rootFolder.GetItemsAsync(i, 1); - - item = results?.FirstOrDefault(); - if (item is null) - break; - } - catch (NotImplementedException) - { - break; - } - catch (Exception ex) when ( - ex is UnauthorizedAccessException || - ex is FileNotFoundException || - (uint)ex.HResult == 0x80070490) // ERROR_NOT_FOUND - { - continue; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Error enumerating directory contents."); - break; - } - - tempList.Add(item); - } - - return tempList; - } - - public static async Task AddFolderAsync( - BaseStorageFolder folder, - StorageFolderWithPath? currentStorageFolder, - CancellationToken cancellationToken) - { - var basicProperties = await folder.GetBasicPropertiesAsync(); - if (!cancellationToken.IsCancellationRequested) - { - if (folder is ShortcutStorageFolder linkFolder) - { - return new ShortcutItem(folder.FolderRelativeId) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = false, - ItemNameRaw = folder.DisplayName, - ItemDateModifiedReal = basicProperties.DateModified, - ItemDateCreatedReal = folder.DateCreated, - ItemType = folder.DisplayType, - ItemPath = folder.Path, - FileSize = null, - FileSizeBytes = 0, - TargetPath = linkFolder.TargetPath, - Arguments = linkFolder.Arguments, - WorkingDirectory = linkFolder.WorkingDirectory, - RunAsAdmin = linkFolder.RunAsAdmin, - ShowWindowCommand = ((int)linkFolder.ShowWindowCommand).ToShowWindowCommand() - }; - } - else if (folder is BinStorageFolder binFolder) - { - return new RecycleBinItem(folder.FolderRelativeId) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = folder.DisplayName, - ItemDateModifiedReal = basicProperties.DateModified, - ItemDateCreatedReal = folder.DateCreated, - ItemType = folder.DisplayType, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = false, - ItemPath = string.IsNullOrEmpty(folder.Path) ? PathNormalization.Combine(currentStorageFolder!.Path, folder.Name) : folder.Path, - FileSize = basicProperties.Size.ToSizeString(), - FileSizeBytes = (long)basicProperties.Size, - ItemDateDeletedReal = binFolder.DateDeleted, - ItemOriginalPath = binFolder.OriginalPath, - }; - } - else - { - return new ListedItem(folder.FolderRelativeId) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = folder.DisplayName, - ItemDateModifiedReal = basicProperties.DateModified, - ItemDateCreatedReal = folder.DateCreated, - ItemType = folder.DisplayType, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = false, - ItemPath = string.IsNullOrEmpty(folder.Path) ? PathNormalization.Combine(currentStorageFolder!.Path, folder.Name) : folder.Path, - FileSize = null, - FileSizeBytes = 0 - }; - } - } - - return null; - } - - public static async Task AddFileAsync( - BaseStorageFile file, - StorageFolderWithPath? currentStorageFolder, - CancellationToken cancellationToken) - { - var basicProperties = await file.GetBasicPropertiesAsync(); - // Display name does not include extension - var itemName = file.Name; - var itemModifiedDate = basicProperties.DateModified; - var itemCreatedDate = file.DateCreated; - var itemPath = string.IsNullOrEmpty(file.Path) ? PathNormalization.Combine(currentStorageFolder!.Path, file.Name) : file.Path; - var itemSize = basicProperties.Size.ToSizeString(); - var itemSizeBytes = basicProperties.Size; - var itemType = file.DisplayType; - var itemFileExtension = file.FileType; - var itemThumbnailImgVis = false; - - if (cancellationToken.IsCancellationRequested) - return null; - - // TODO: is this needed to be handled here? - if (App.LibraryManager.TryGetLibrary(file.Path, out var library)) - { - return new LibraryItem(library) - { - Opacity = 1, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - }; - } - else - { - if (file is ShortcutStorageFile linkFile) - { - var isUrl = FileExtensionHelpers.IsWebLinkFile(linkFile.Name); - return new ShortcutItem(file.FolderRelativeId) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = itemType, - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = (long)itemSizeBytes, - TargetPath = linkFile.TargetPath, - Arguments = linkFile.Arguments, - WorkingDirectory = linkFile.WorkingDirectory, - RunAsAdmin = linkFile.RunAsAdmin, - ShowWindowCommand = ((int)linkFile.ShowWindowCommand).ToShowWindowCommand(), - IsUrl = isUrl, - }; - } - else if (file is BinStorageFile binFile) - { - return new RecycleBinItem(file.FolderRelativeId) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = itemType, - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = (long)itemSizeBytes, - ItemDateDeletedReal = binFile.DateDeleted, - ItemOriginalPath = binFile.OriginalPath - }; - } - else - { - return new ListedItem(file.FolderRelativeId) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = itemType, - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = (long)itemSizeBytes, - }; - } - } - } - } -} diff --git a/src/Files.App/Utils/Storage/Enumerators/Win32StorageEnumerator.Windows.cs b/src/Files.App/Utils/Storage/Enumerators/Win32StorageEnumerator.Windows.cs deleted file mode 100644 index 9ffbeac5944a..000000000000 --- a/src/Files.App/Utils/Storage/Enumerators/Win32StorageEnumerator.Windows.cs +++ /dev/null @@ -1,493 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Services.SizeProvider; -using Files.Shared.Helpers; -using System.IO; -using Windows.Storage; -using FileAttributes = System.IO.FileAttributes; - -namespace Files.App.Utils.Storage -{ - public static class Win32StorageEnumerator - { - private static readonly ISizeProvider folderSizeProvider = Ioc.Default.GetRequiredService(); - private static readonly IStorageCacheService fileListCache = Ioc.Default.GetRequiredService(); - - private static readonly string folderTypeTextLocalized = Strings.Folder.GetLocalizedResource(); - - private static readonly IIconCacheService iconCacheService = Ioc.Default.GetRequiredService(); - - public static async Task> ListEntries( - string path, - Win32PInvoke.SafeFindHandle hFile, - Win32PInvoke.WIN32_FIND_DATA findData, - CancellationToken cancellationToken, - int countLimit, - uint iconSize, - Func, Task> intermediateAction - ) - { - var sampler = new IntervalSampler(500); - // Intermediate flushes merge in sorted, so an early first paint costs no reshuffle later - var firstBatchSampler = new IntervalSampler(25); - var hasFlushedFirstBatch = false; - var tempList = new List(); - var count = 0; - - IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService(); - bool CalculateFolderSizes = userSettingsService.FoldersSettingsService.CalculateFolderSizes; - bool showHiddenItems = userSettingsService.FoldersSettingsService.ShowHiddenItems; - bool showProtectedSystemFiles = userSettingsService.FoldersSettingsService.ShowProtectedSystemFiles; - bool showDotFiles = userSettingsService.FoldersSettingsService.ShowDotFiles; - bool areAlternateStreamsVisible = userSettingsService.FoldersSettingsService.AreAlternateStreamsVisible; - - var isGitRepo = GitHelpers.IsRepositoryEx(path, out var repoPath) && !string.IsNullOrEmpty(await GitHelpers.GetRepositoryHeadName(repoPath)); - var rawHandle = hFile.DangerousGetHandle(); - - try - { - do - { - var isSystem = ((FileAttributes)findData.dwFileAttributes & FileAttributes.System) == FileAttributes.System; - var isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - var startWithDot = findData.cFileName.StartsWith('.'); - if ((!isHidden || - (showHiddenItems && - (!isSystem || showProtectedSystemFiles))) && - (!startWithDot || showDotFiles)) - { - if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory) - { - var file = await GetFile(findData, path, isGitRepo, cancellationToken); - if (file is not null) - { - var filePath = file.ItemPath!; - file.PreloadedIconData = await iconCacheService.GetIconAsync(file.ItemPath, file.FileExtension, false, iconSize); - tempList.Add(file); - ++count; - - if (areAlternateStreamsVisible) - tempList.AddRange(EnumAdsForPath(filePath, file)); - } - } - else if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory) - { - if (findData.cFileName != "." && findData.cFileName != "..") - { - var folder = await GetFolder(findData, path, isGitRepo, cancellationToken); - if (folder is not null) - { - var folderPath = folder.ItemPath!; - folder.PreloadedIconData = await iconCacheService.GetIconAsync(folder.ItemPath, null, true, iconSize); - tempList.Add(folder); - ++count; - - if (areAlternateStreamsVisible) - tempList.AddRange(EnumAdsForPath(folderPath, folder)); - - if (CalculateFolderSizes) - { - if (folderSizeProvider.TryGetSize(folderPath, out var size)) - { - folder.FileSizeBytes = (long)size; - folder.FileSize = size.ToSizeString(); - } - - _ = folderSizeProvider.UpdateAsync(folderPath, cancellationToken); - } - } - } - } - } - - if (cancellationToken.IsCancellationRequested || count == countLimit) - break; - - if (intermediateAction is not null && - (hasFlushedFirstBatch - ? sampler.CheckNow() - : tempList.Count > 0 && firstBatchSampler.CheckNow())) - { - hasFlushedFirstBatch = true; - await intermediateAction(tempList); - - // clear the temporary list every time we do an intermediate action - tempList.Clear(); - } - } while (Win32PInvoke.FindNextFile(rawHandle, out findData)); - } - finally - { - hFile.Dispose(); - } - - return tempList; - } - - private static IEnumerable EnumAdsForPath(string itemPath, ListedItem main) - { - foreach (var ads in Win32Helper.GetAlternateStreams(itemPath)) - yield return GetAlternateStream(ads, main); - } - - public static ListedItem GetAlternateStream((string Name, long Size) ads, ListedItem main) - { - string itemType = Strings.File.GetLocalizedResource(); - string? itemFileExtension = null; - - if (ads.Name.Contains('.')) - { - itemFileExtension = Path.GetExtension(ads.Name); - itemType = itemFileExtension!.Trim('.') + " " + itemType; - } - - string adsName = ads.Name.Substring(1, ads.Name.Length - 7); // Remove ":" and ":$DATA" - - return new AlternateStreamItem() - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - FileImage = null, - LoadFileIcon = false, - ItemNameRaw = adsName, - IsHiddenItem = false, - Opacity = Constants.UI.DimItemOpacity, - ItemDateModifiedReal = main.ItemDateModifiedReal, - ItemDateAccessedReal = main.ItemDateAccessedReal, - ItemDateCreatedReal = main.ItemDateCreatedReal, - ItemType = itemType, - ItemPath = $"{main.ItemPath}:{adsName}", - FileSize = ads.Size.ToSizeString(), - FileSizeBytes = ads.Size - }; - } - - public static async Task GetFolder( - Win32PInvoke.WIN32_FIND_DATA findData, - string pathRoot, - bool isGitRepo, - CancellationToken cancellationToken - ) - { - if (cancellationToken.IsCancellationRequested) - return null; - - DateTime itemModifiedDate; - DateTime itemCreatedDate; - - try - { - Win32PInvoke.FileTimeToSystemTime(in findData.ftLastWriteTime, out Win32PInvoke.SYSTEMTIME systemModifiedTimeOutput); - itemModifiedDate = systemModifiedTimeOutput.ToDateTime(); - - Win32PInvoke.FileTimeToSystemTime(in findData.ftCreationTime, out Win32PInvoke.SYSTEMTIME systemCreatedTimeOutput); - itemCreatedDate = systemCreatedTimeOutput.ToDateTime(); - } - catch (ArgumentException) - { - // Invalid date means invalid findData, do not add to list - return null; - } - - var itemPath = Path.Combine(pathRoot, findData.cFileName); - - string itemName = await fileListCache.GetDisplayName(itemPath, cancellationToken); - if (string.IsNullOrEmpty(itemName)) - { - itemName = findData.cFileName; - - // The shell only reads desktop.ini for folders marked ReadOnly or System, and keeps the raw name for junctions - const FileAttributes desktopIniFlags = FileAttributes.ReadOnly | FileAttributes.System; - var attributes = (FileAttributes)findData.dwFileAttributes; - if ((attributes & desktopIniFlags) != 0 && (attributes & FileAttributes.ReparsePoint) == 0) - itemName = Win32Helper.GetLocalizedName(itemPath) ?? itemName; - } - - bool isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden); - double opacity = 1; - - if (isHidden) - opacity = Constants.UI.DimItemOpacity; - - if (isGitRepo) - { - return new GitItem() - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = folderTypeTextLocalized, - FileImage = null, - IsHiddenItem = isHidden, - Opacity = opacity, - LoadFileIcon = false, - ItemPath = itemPath, - FileSize = null, - FileSizeBytes = 0, - }; - } - else - { - return new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = folderTypeTextLocalized, - FileImage = null, - IsHiddenItem = isHidden, - Opacity = opacity, - LoadFileIcon = false, - ItemPath = itemPath, - FileSize = null, - FileSizeBytes = 0, - }; - } - } - - public static async Task GetFile( - Win32PInvoke.WIN32_FIND_DATA findData, - string pathRoot, - bool isGitRepo, - CancellationToken cancellationToken - ) - { - var itemPath = Path.Combine(pathRoot, findData.cFileName); - var itemName = findData.cFileName; - - DateTime itemModifiedDate, itemCreatedDate, itemLastAccessDate; - - try - { - Win32PInvoke.FileTimeToSystemTime(in findData.ftLastWriteTime, out Win32PInvoke.SYSTEMTIME systemModifiedDateOutput); - itemModifiedDate = systemModifiedDateOutput.ToDateTime(); - - Win32PInvoke.FileTimeToSystemTime(in findData.ftCreationTime, out Win32PInvoke.SYSTEMTIME systemCreatedDateOutput); - itemCreatedDate = systemCreatedDateOutput.ToDateTime(); - - Win32PInvoke.FileTimeToSystemTime(in findData.ftLastAccessTime, out Win32PInvoke.SYSTEMTIME systemLastAccessOutput); - itemLastAccessDate = systemLastAccessOutput.ToDateTime(); - } - catch (ArgumentException) - { - // Invalid date means invalid findData, do not add to list - return null; - } - - long itemSizeBytes = findData.GetSize(); - var itemSize = itemSizeBytes.ToSizeString(); - string itemType = Strings.File.GetLocalizedResource(); - string? itemFileExtension = null; - - if (findData.cFileName.Contains('.')) - { - itemFileExtension = Path.GetExtension(itemPath); - - // Resolve the localized type here (cached by extension) so it's correct from the first paint and sorts right - var localizedType = FileTypesHelper.GetLocalizedTypeName(itemFileExtension); - itemType = !string.IsNullOrEmpty(localizedType) - ? localizedType - : itemFileExtension!.Trim('.') + " " + itemType; - } - - bool itemThumbnailImgVis = false; - - if (cancellationToken.IsCancellationRequested) - return null; - - bool isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - double opacity = isHidden ? Constants.UI.DimItemOpacity : 1; - - // https://learn.microsoft.com/openspecs/windows_protocols/ms-fscc/c8e77b37-3909-4fe6-a4ea-2b9d423b1ee4 - bool isReparsePoint = ((FileAttributes)findData.dwFileAttributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint; - bool isSymlink = isReparsePoint && findData.dwReserved0 == Win32PInvoke.IO_REPARSE_TAG_SYMLINK; - - if (isSymlink) - { - var targetPath = Win32Helper.ParseSymLink(itemPath); - if (isGitRepo) - { - return new GitShortcutItem() - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = isHidden, - Opacity = opacity, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = Strings.Shortcut.GetLocalizedResource(), - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes, - TargetPath = targetPath, - IsSymLink = true, - }; - } - else - { - return new ShortcutItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = isHidden, - Opacity = opacity, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = Strings.Shortcut.GetLocalizedResource(), - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes, - TargetPath = targetPath, - IsSymLink = true - }; - } - } - else if (FileExtensionHelpers.IsShortcutOrUrlFile(findData.cFileName)) - { - var isUrl = FileExtensionHelpers.IsWebLinkFile(findData.cFileName); - - // Listing only needs the data stored in the link file; resolving the target - // can block on moved or unreachable targets and is done when the item is opened - var shInfo = await FileOperationsHelpers.ParseLinkAsync(itemPath, resolveTarget: false); - if (shInfo is null) - return null; - - if (isGitRepo) - { - return new GitShortcutItem() - { - PrimaryItemAttribute = shInfo.IsFolder ? StorageItemTypes.Folder : StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = isHidden, - Opacity = opacity, - FileImage = null, - LoadFileIcon = !shInfo.IsFolder && itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = isUrl ? Strings.ShortcutWebLinkFileType.GetLocalizedResource() : Strings.Shortcut.GetLocalizedResource(), - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes, - TargetPath = shInfo.TargetPath, - Arguments = shInfo.Arguments, - WorkingDirectory = shInfo.WorkingDirectory, - RunAsAdmin = shInfo.RunAsAdmin, - ShowWindowCommand = ((int)shInfo.ShowWindowCommand).ToShowWindowCommand(), - IsUrl = isUrl, - }; - } - else - { - return new ShortcutItem(null) - { - PrimaryItemAttribute = shInfo.IsFolder ? StorageItemTypes.Folder : StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = isHidden, - Opacity = opacity, - FileImage = null, - LoadFileIcon = !shInfo.IsFolder && itemThumbnailImgVis, - ItemNameRaw = itemName, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = isUrl ? Strings.ShortcutWebLinkFileType.GetLocalizedResource() : Strings.Shortcut.GetLocalizedResource(), - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes, - TargetPath = shInfo.TargetPath, - Arguments = shInfo.Arguments, - WorkingDirectory = shInfo.WorkingDirectory, - RunAsAdmin = shInfo.RunAsAdmin, - ShowWindowCommand = ((int)shInfo.ShowWindowCommand).ToShowWindowCommand(), - IsUrl = isUrl, - }; - } - } - else if (App.LibraryManager.TryGetLibrary(itemPath, out var library)) - { - return new LibraryItem(library) - { - Opacity = opacity, - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - }; - } - else - { - if (ZipStorageFolder.IsZipPath(itemPath) && await ZipStorageFolder.CheckDefaultZipApp(itemPath)) - { - return new ZipItem(null) - { - PrimaryItemAttribute = StorageItemTypes.Folder, // Treat zip files as folders - FileExtension = itemFileExtension, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - IsHiddenItem = isHidden, - Opacity = opacity, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = itemType, - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes - }; - } - else if (isGitRepo) - { - return new GitItem() - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - IsHiddenItem = isHidden, - Opacity = opacity, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = itemType, - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes - }; - } - else - { - return new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - FileImage = null, - LoadFileIcon = itemThumbnailImgVis, - ItemNameRaw = itemName, - IsHiddenItem = isHidden, - Opacity = opacity, - ItemDateModifiedReal = itemModifiedDate, - ItemDateAccessedReal = itemLastAccessDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = itemType, - ItemPath = itemPath, - FileSize = itemSize, - FileSizeBytes = itemSizeBytes - }; - } - } - } - } -} diff --git a/src/Files.App/Utils/Storage/Helpers/ArchiveEntryHelpers.cs b/src/Files.App/Utils/Storage/Helpers/ArchiveEntryHelpers.cs deleted file mode 100644 index f09a95673f38..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/ArchiveEntryHelpers.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -#if WINDOWS -using SevenZip; -using IO = System.IO; - -namespace Files.App.Utils.Storage -{ - public static class ArchiveEntryHelpers - { - // SevenZipSharp reports this placeholder for entries with no stored name, - // e.g. gzip archives created without the optional FNAME header field. - private const string NamelessEntryPlaceholder = "[no name]"; - - /// - /// Gets the archive's entries with each nameless entry renamed via . - /// - public static IEnumerable GetArchiveFileData(this SevenZipExtractor extractor, string containerPath) - { - return extractor.ArchiveFileData.Select(entry => - { - entry.FileName = GetEntryName(entry, containerPath); - return entry; - }); - } - - /// - /// Gets the name of an archive entry, substituting the archive's own file name - /// without its extension when the entry has no stored name, as 7-Zip does. - /// - public static string GetEntryName(ArchiveFileInfo entry, string containerPath) - { - if (!string.IsNullOrEmpty(entry.FileName) && entry.FileName != NamelessEntryPlaceholder) - return entry.FileName; - - var fallback = IO.Path.GetFileNameWithoutExtension(containerPath); - return string.IsNullOrEmpty(fallback) ? NamelessEntryPlaceholder : fallback; - } - } -} - -#endif diff --git a/src/Files.App/Utils/Storage/Helpers/DriveHelpers.cs b/src/Files.App/Utils/Storage/Helpers/DriveHelpers.cs deleted file mode 100644 index 0ab4ade3547d..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/DriveHelpers.cs +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using DiscUtils.Udf; -using Windows.Devices.Enumeration; -using Windows.Devices.Portable; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Win32; -using Windows.Win32.Foundation; - -namespace Files.App.Utils.Storage -{ - public static class DriveHelpers - { - public static async void EjectDeviceAsync(string path) - { - await ContextMenu.InvokeVerb("eject", path); - } - - public static async Task CheckEmptyDrive(string? drivePath) - { - if (string.IsNullOrWhiteSpace(drivePath)) - return false; - var drivesViewModel = Ioc.Default.GetRequiredService(); - - var matchingDrive = drivesViewModel.Drives.Cast().FirstOrDefault(x => drivePath.StartsWith(x.Path!, StringComparison.Ordinal)); - if (matchingDrive is null || matchingDrive.Type != Data.Items.DriveType.CDRom || matchingDrive.MaxSpace != ByteSizeLib.ByteSize.FromBytes(0)) - return false; - - var ejectButton = await DialogDisplayHelper.ShowDialogAsync( - Strings.InsertDiscDialogTitle.GetLocalizedResource(), - string.Format(Strings.InsertDiscDialogText.GetLocalizedResource(), matchingDrive.Path), - Strings.InsertDiscDialog_OpenDriveButton.GetLocalizedResource(), - Strings.Close.GetLocalizedResource()); - if (ejectButton) - EjectDeviceAsync(matchingDrive.Path!); - return true; - } - - public static async Task GetRootFromPathAsync(string? devicePath) - { - if (!SystemIO.Path.IsPathRooted(devicePath)) - return null; - - var drivesViewModel = Ioc.Default.GetRequiredService(); - - var rootPath = SystemIO.Path.GetPathRoot(devicePath); - if (rootPath is null) - return null; - - if (devicePath.StartsWith(@"\\?\", StringComparison.Ordinal)) // USB device - { - // Check among already discovered drives - StorageFolder? matchingDrive = drivesViewModel.Drives.Cast().FirstOrDefault(x => - Helpers.PathNormalization.NormalizePath(x.Path) == Helpers.PathNormalization.NormalizePath(rootPath))?.Root; - if (matchingDrive is null) - { - // Check on all removable drives - var remDevices = await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector()); - string normalizedRootPath = Helpers.PathNormalization.NormalizePath(rootPath).Replace(@"\\?\", string.Empty, StringComparison.Ordinal); - foreach (var item in remDevices) - { - try - { - var root = StorageDevice.FromId(item.Id); - if (normalizedRootPath == root.Name.ToUpperInvariant()) - { - matchingDrive = root; - break; - } - } - catch (Exception) - { - // Ignore this.. - } - } - } - if (matchingDrive is not null) - { - return new StorageFolderWithPath(matchingDrive, rootPath); - } - } - // Network share - else if ( - (devicePath.StartsWith(@"\\", StringComparison.Ordinal) || - GetDriveType(new SystemIO.DriveInfo(devicePath)) is DriveType.Network) && - !devicePath.StartsWith(@"\\SHELL\", StringComparison.Ordinal) - ) - { - int lastSepIndex = rootPath.LastIndexOf('\\'); - rootPath = lastSepIndex > 1 ? rootPath.Substring(0, lastSepIndex) : rootPath; // Remove share name - return new StorageFolderWithPath(await StorageFolder.GetFolderFromPathAsync(rootPath), rootPath); - } - // It's ok to return null here, on normal drives StorageFolder.GetFolderFromPathAsync works - return null; - } - - public static bool IsMtpPath(string path) - { - return path.StartsWith(@"\\?\", StringComparison.Ordinal); - } - - public static bool IsNetworkPath(string path) - { - if (IsMtpPath(path)) - return false; - - try - { - return path.StartsWith(@"\\", StringComparison.Ordinal) || - GetDriveType(new SystemIO.DriveInfo(path)) is Data.Items.DriveType.Network; - } - catch - { - return false; - } - } - - // Per-item network classification matching enumeration rules; the drive-type probe runs off the UI thread as it can block on an unreachable drive. - public static Task IsNetworkStorageItemAsync(string path) - { - if (path.StartsWith(@"\\", StringComparison.Ordinal)) - { - // MTP, WSL and shell-namespace paths aren't network shares - return Task.FromResult(!IsMtpPath(path) - && !path.StartsWith(@"\\SHELL\", StringComparison.Ordinal) - && !path.StartsWith(@"\\wsl$\", StringComparison.OrdinalIgnoreCase) - && !path.StartsWith(@"\\wsl.localhost\", StringComparison.OrdinalIgnoreCase)); - } - - var root = SystemIO.Path.GetPathRoot(path); - if (string.IsNullOrEmpty(root)) - return Task.FromResult(false); - - return Task.Run(() => - { - try { return new SystemIO.DriveInfo(root).DriveType == SystemIO.DriveType.Network; } - catch { return false; } - }); - } - - public static Data.Items.DriveType GetDriveType(System.IO.DriveInfo drive) - { - if (drive.DriveType is System.IO.DriveType.Unknown) - { - string path = PathNormalization.NormalizePath(drive.Name); - - if (path is "A:" or "B:") - return Data.Items.DriveType.FloppyDisk; - } - - return drive.DriveType switch - { - SystemIO.DriveType.CDRom => Data.Items.DriveType.CDRom, - SystemIO.DriveType.Fixed => Data.Items.DriveType.Fixed, - SystemIO.DriveType.Network => Data.Items.DriveType.Network, - SystemIO.DriveType.NoRootDirectory => Data.Items.DriveType.NoRootDirectory, - SystemIO.DriveType.Ram => Data.Items.DriveType.Ram, - SystemIO.DriveType.Removable => Data.Items.DriveType.Removable, - _ => Data.Items.DriveType.Unknown, - }; - } - - public static unsafe string GetExtendedDriveLabel(SystemIO.DriveInfo drive) - { - return SafetyExtensions.IgnoreExceptions(() => - { - if (drive.DriveType is not SystemIO.DriveType.CDRom || drive.DriveFormat is not "UDF") - return drive.VolumeLabel; - - return SafetyExtensions.IgnoreExceptions(() => - { - string dosDevicePath = ""; - - fixed (char* cDeviceName = drive.Name) - { - var cch = PInvoke.QueryDosDevice(cDeviceName, null, 0u); - - fixed (char* cTargetPath = new char[cch]) - { - PWSTR pszTargetPath = new(cTargetPath); - PInvoke.QueryDosDevice(cDeviceName, pszTargetPath, 0u); - dosDevicePath = pszTargetPath.ToString(); - } - } - - if (string.IsNullOrEmpty(dosDevicePath)) - return drive.VolumeLabel; - - using var driveStream = new SystemIO.FileStream( - dosDevicePath.Replace(@"\Device\", @"\\.\"), - SystemIO.FileMode.Open, - SystemIO.FileAccess.Read); - - using var udf = new UdfReader(driveStream); - - return udf.VolumeLabel; - }) ?? drive.VolumeLabel; - - }) ?? ""; - } - - public static async Task GetThumbnailAsync(StorageFolder folder) - => await FilesystemTasks.Wrap(() - => folder.GetThumbnailAsync(ThumbnailMode.SingleItem, 40, ThumbnailOptions.UseCurrentScale).AsTask() - ); - } -} diff --git a/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs b/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs index fb512622fcdf..635d9d5691ef 100644 --- a/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs +++ b/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs @@ -9,9 +9,6 @@ using Microsoft.UI.Xaml.Media.Animation; using System.Collections.Concurrent; using Windows.Graphics; -#if WINDOWS -using Windows.Win32; -#endif namespace Files.App.Utils.Storage { @@ -142,10 +139,6 @@ public static void OpenPropertiesWindow(object item, IShellPage associatedInstan // WINUI3: Move window to cursor position (the window manager places the window on Linux) var pointerPosition = default(System.Drawing.Point); -#if WINDOWS - if (!OperatingSystem.IsLinux()) - PInvoke.GetCursorPos(out pointerPosition); -#endif // Null when no display is available, e.g. while monitors are detached var displayArea = OperatingSystem.IsLinux() diff --git a/src/Files.App/Utils/Storage/Helpers/FileThumbnailHelper.cs b/src/Files.App/Utils/Storage/Helpers/FileThumbnailHelper.cs index f20c604ddb48..cf7336d1296e 100644 --- a/src/Files.App/Utils/Storage/Helpers/FileThumbnailHelper.cs +++ b/src/Files.App/Utils/Storage/Helpers/FileThumbnailHelper.cs @@ -25,37 +25,9 @@ public static class FileThumbnailHelper ? Math.Max(1u, (uint)Math.Round(scaledSize)) : _standardSizes.FirstOrDefault(s => s >= scaledSize, _standardSizes[^1]); -#if !WINDOWS // Linux theme SVGs and thumbnailers accept the actual pixel size, including HiDPI cells above 256px. size = Math.Clamp((uint)Math.Ceiling(scaledSize), 1u, 1024u); return await LinuxIconHelper.GetIconAsync(path, size, isFolder, iconOptions, cancellationToken); -#else - if (!isFolder && !iconOptions.HasFlag(IconOptions.ReturnIconOnly) && !iconOptions.HasFlag(IconOptions.ReturnOnlyIfCached)) - { - var extension = Path.GetExtension(path); - - //Restrict to only %windir%\fonts - if (FileExtensionHelpers.IsFontFile(extension) && path is not null && PathHelpers.IsInSystemFontsFolder(path)) - { - var winrtThumbnail = await FontFileHelper.GetWinRTThumbnailAsync(path, (uint)size); - if (winrtThumbnail is not null) - return winrtThumbnail; - - if (!string.Equals(extension, ".fon", StringComparison.OrdinalIgnoreCase)) - { - var fontThumbnail = await STATask.Run(() => FontFileHelper.GenerateFontThumbnail(path, (int)size), App.Logger); - if (fontThumbnail is not null) - return fontThumbnail; - } - } - } - - var resolvedPath = path is not null && path.StartsWith(@"\\?\", StringComparison.Ordinal) - ? MtpHelpers.ResolveMtpShellPath(path) ?? path - : path; - - return await STATask.RunPooled(() => Win32Helper.GetIcon(resolvedPath, (int)size, isFolder, iconOptions), App.Logger); -#endif } /// @@ -67,14 +39,9 @@ public static class FileThumbnailHelper public static async Task GetIconOverlayAsync(string? path, uint requestedSize, bool isFolder) { // Overlays render at 32px in thumbnail layouts and 16px in details/columns; scale by DPI so the badge isn't upscaled at fractional scaling -#if !WINDOWS // Only the symlink emblem exists on Linux; cloud/sync status has no freedesktop equivalent var overlaySize = (requestedSize >= 48 ? 32u : 16u) * App.AppModel.AppWindowDPI; return await LinuxIconHelper.GetOverlayAsync(path, (uint)overlaySize); -#else - var overlaySize = (requestedSize >= 48 ? 32u : 16u) * App.AppModel.AppWindowDPI; - return await STATask.RunPooled(() => Win32Helper.GetIconOverlay(path, (int)overlaySize, isFolder), App.Logger); -#endif } [Obsolete] diff --git a/src/Files.App/Utils/Storage/Helpers/FileTypesHelper.cs b/src/Files.App/Utils/Storage/Helpers/FileTypesHelper.cs index ec35c9171723..273ca89ee406 100644 --- a/src/Files.App/Utils/Storage/Helpers/FileTypesHelper.cs +++ b/src/Files.App/Utils/Storage/Helpers/FileTypesHelper.cs @@ -2,11 +2,6 @@ // SPDX-License-Identifier: MPL-2.0 using System.Collections.Concurrent; -#if WINDOWS -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.UI.Shell; -#endif namespace Files.App.Utils.Storage { @@ -27,32 +22,7 @@ public static unsafe string GetLocalizedTypeName(string? extension) if (!OperatingSystem.IsWindows()) return string.Empty; -#if WINDOWS - if (typeNameCache.TryGetValue(extension, out var cached)) - return cached; - - var typeName = string.Empty; - SHFILEINFOW shfi = default; - - fixed (char* pExtension = extension) - { - // SHGFI_USEFILEATTRIBUTES resolves from the extension alone, so this never touches disk - var result = PInvoke.SHGetFileInfo( - pExtension, - FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_NORMAL, - &shfi, - (uint)sizeof(SHFILEINFOW), - SHGFI_FLAGS.SHGFI_TYPENAME | SHGFI_FLAGS.SHGFI_USEFILEATTRIBUTES); - - if (result != 0 && shfi.szTypeName.Value[0] != '\0') - typeName = shfi.szTypeName.ToString(); - } - - typeNameCache[extension] = typeName; - return typeName; -#else return string.Empty; -#endif } } } diff --git a/src/Files.App/Utils/Storage/Helpers/FilesystemResult.cs b/src/Files.App/Utils/Storage/Helpers/FilesystemResult.cs index e0550dbbefbf..997bf8a22614 100644 --- a/src/Files.App/Utils/Storage/Helpers/FilesystemResult.cs +++ b/src/Files.App/Utils/Storage/Helpers/FilesystemResult.cs @@ -1,9 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if WINDOWS -using Windows.Win32.Foundation; -#endif namespace Files.App.Utils.Storage { @@ -20,10 +17,6 @@ public class FilesystemResult public static explicit operator FilesystemResult(bool res) => new(res ? FileSystemStatusCode.Success : FileSystemStatusCode.Generic); -#if WINDOWS - public static implicit operator BOOL(FilesystemResult? res) => res?.ErrorCode is FileSystemStatusCode.Success; - public static explicit operator FilesystemResult(BOOL res) => new(res ? FileSystemStatusCode.Success : FileSystemStatusCode.Generic); -#endif } public sealed class FilesystemResult : FilesystemResult diff --git a/src/Files.App/Utils/Storage/Helpers/FolderHelpers.cs b/src/Files.App/Utils/Storage/Helpers/FolderHelpers.cs index 6dfe0e8e89bc..1f3c05ea1ef8 100644 --- a/src/Files.App/Utils/Storage/Helpers/FolderHelpers.cs +++ b/src/Files.App/Utils/Storage/Helpers/FolderHelpers.cs @@ -2,12 +2,6 @@ // Licensed under the MIT License. using System.IO; -#if WINDOWS -using Windows.Win32; -#endif -#if WINDOWS -using Windows.Win32.Storage.FileSystem; -#endif namespace Files.App.Utils.Storage { @@ -17,17 +11,9 @@ public static class FolderHelpers { public static unsafe bool CheckFolderAccessWithWin32(string path) { -#if !WINDOWS return SafeEnumerates(path); -#else - WIN32_FIND_DATAW findData = default; - using FindCloseSafeHandle hFile = PInvoke.FindFirstFileEx($"{path}{Path.DirectorySeparatorChar}*.*", FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - return !hFile.IsInvalid; -#endif } -#if !WINDOWS // Opening the directory for listing is the access test (an empty readable folder is accessible) private static bool SafeEnumerates(string path) { @@ -42,7 +28,6 @@ private static bool SafeEnumerates(string path) return false; } } -#endif public static async Task CheckBitlockerStatusAsync(BaseStorageFolder? rootFolder, string path) { @@ -66,7 +51,6 @@ public static async Task CheckBitlockerStatusAsync(BaseStorageFolder? root /// public static unsafe bool CheckForFilesFolders(string targetPath) { -#if !WINDOWS try { using var e = Directory.EnumerateFileSystemEntries(targetPath).GetEnumerator(); @@ -76,29 +60,11 @@ public static unsafe bool CheckForFilesFolders(string targetPath) { return false; } -#else - WIN32_FIND_DATAW findData = default; - using FindCloseSafeHandle hFile = PInvoke.FindFirstFileEx($"{targetPath}{Path.DirectorySeparatorChar}*.*", FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - if (hFile.IsInvalid) - return false; - - do - { - string fileName = findData.cFileName.ToString(); - if (fileName is not "." and not "..") - return true; - } - while (PInvoke.FindNextFile(hFile, out findData)); - - return false; -#endif } public static unsafe List EnumerateSubfolders(string path, bool showHidden, bool showProtected, bool showDot, int limit = 1000) { var results = new List(); -#if !WINDOWS try { foreach (var dir in new DirectoryInfo(path).EnumerateDirectories()) @@ -122,54 +88,10 @@ public static unsafe List EnumerateSubfolders(string path, bool var comparer = NaturalStringComparer.GetForProcessor(); results.Sort((a, b) => comparer.Compare(a.Name, b.Name)); return results; -#else - WIN32_FIND_DATAW findData = default; - using FindCloseSafeHandle hFind = PInvoke.FindFirstFileEx( - path + "\\*.*", - FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - if (hFind.IsInvalid) - return results; - - do - { - var attrs = (FileAttributes)findData.dwFileAttributes; - if ((attrs & FileAttributes.Directory) != FileAttributes.Directory) - continue; - - string fileName = findData.cFileName.ToString(); - if (fileName is "." or "..") - continue; - - var isHidden = (attrs & FileAttributes.Hidden) == FileAttributes.Hidden; - var isSystem = (attrs & FileAttributes.System) == FileAttributes.System; - - if (!showDot && fileName.StartsWith('.')) - continue; - if (isHidden && !showHidden) - continue; - if (isHidden && isSystem && !showProtected) - continue; - - var subPath = Path.Combine(path, fileName); - results.Add(new SubfolderEntry(subPath, fileName, HasSubfolders(subPath), isHidden)); - - if (results.Count == limit) - break; - } - while (PInvoke.FindNextFile(hFind, out findData)); - - var naturalComparer = NaturalStringComparer.GetForProcessor(); - results.Sort((a, b) => naturalComparer.Compare(a.Name, b.Name)); - return results; -#endif } public static unsafe bool HasSubfolders(string path) { -#if !WINDOWS try { using var e = Directory.EnumerateDirectories(path).GetEnumerator(); @@ -179,28 +101,6 @@ public static unsafe bool HasSubfolders(string path) { return false; } -#else - WIN32_FIND_DATAW findData = default; - using FindCloseSafeHandle hFind = PInvoke.FindFirstFileEx( - path + "\\*.*", - FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - if (hFind.IsInvalid) - return false; - - do - { - string fileName = findData.cFileName.ToString(); - if (fileName is "." or "..") - continue; - if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory) - return true; - } - while (PInvoke.FindNextFile(hFind, out findData)); - return false; -#endif } } } diff --git a/src/Files.App/Utils/Storage/Helpers/FontFileHelper.cs b/src/Files.App/Utils/Storage/Helpers/FontFileHelper.cs deleted file mode 100644 index 33f87170ffbe..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/FontFileHelper.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using Microsoft.Extensions.Logging; -using Microsoft.Graphics.Canvas.Text; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.Drawing.Text; -using System.IO; -using Windows.Storage; -using Windows.Storage.FileProperties; - -namespace Files.App.Utils.Storage -{ - public static class FontFileHelper - { - private const float FontSizeRatio = 0.35f; - private const string PreviewText = "Abg"; - - public static async Task GetWinRTThumbnailAsync(string fontPath, uint size) - { - StorageFile? file = null; - StorageItemThumbnail? thumbnail = null; - try - { - file = await StorageFile.GetFileFromPathAsync(fontPath); - thumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, size); - - if (thumbnail is null || thumbnail.Size == 0) - { - return null; - } - - using (var stream = thumbnail.AsStream()) - { - using var memoryStream = new MemoryStream((int)thumbnail.Size); - await stream.CopyToAsync(memoryStream); - - return memoryStream.ToArray(); - } - } - catch (Exception ex) - { - App.Logger.LogError(ex, $"Exception while getting WinRT thumbnail for {LogPathHelper.RedactPath(fontPath)}."); - return null; - } - finally - { - thumbnail?.Dispose(); - } - } - - public static byte[]? GenerateFontThumbnail(string fontPath, int size) - { - try - { - if (!File.Exists(fontPath)) - return null; - - using var fontCollection = new PrivateFontCollection(); - fontCollection.AddFontFile(fontPath); - - if (fontCollection.Families.Length == 0) - return null; - - var fontFamily = fontCollection.Families[0]; - var style = GetAvailableFontStyle(fontFamily); - - using var bitmap = new Bitmap(size, size); - using var graphics = Graphics.FromImage(bitmap); - - graphics.Clear(Color.White); - graphics.SmoothingMode = SmoothingMode.AntiAlias; - graphics.TextRenderingHint = TextRenderingHint.AntiAlias; - - var fontSize = size * FontSizeRatio; - using var font = new Font(fontFamily, fontSize, style, GraphicsUnit.Pixel); - - var textSize = graphics.MeasureString(PreviewText, font); - - var x = (size - textSize.Width) / 2; - var y = (size - textSize.Height) / 2; - - using var brush = new SolidBrush(Color.Black); - graphics.DrawString(PreviewText, font, brush, x, y); - - using var ms = new MemoryStream(); - bitmap.Save(ms, ImageFormat.Png); - return ms.ToArray(); - } - catch (Exception ex) - { - App.Logger.LogError(ex, $"Exception while generating font thumbnail for {LogPathHelper.RedactPath(fontPath)}."); - return null; - } - } - - private static FontStyle GetAvailableFontStyle(FontFamily fontFamily) - { - if (fontFamily.IsStyleAvailable(FontStyle.Regular)) - return FontStyle.Regular; - if (fontFamily.IsStyleAvailable(FontStyle.Bold)) - return FontStyle.Bold; - if (fontFamily.IsStyleAvailable(FontStyle.Italic)) - return FontStyle.Italic; - if (fontFamily.IsStyleAvailable(FontStyle.Bold | FontStyle.Italic)) - return FontStyle.Bold | FontStyle.Italic; - - return FontStyle.Regular; - } - } -} diff --git a/src/Files.App/Utils/Storage/Helpers/IStorageItemWithPath.cs b/src/Files.App/Utils/Storage/Helpers/IStorageItemWithPath.cs index a1f38d43f438..46e66d503b86 100644 --- a/src/Files.App/Utils/Storage/Helpers/IStorageItemWithPath.cs +++ b/src/Files.App/Utils/Storage/Helpers/IStorageItemWithPath.cs @@ -13,9 +13,6 @@ public interface IStorageItemWithPath public string Path { get; } -#if WINDOWS - public IStorageItem? Item { get; } -#endif /// /// Gets the storable for this item, if one has been resolved; otherwise, . diff --git a/src/Files.App/Utils/Storage/Helpers/MtpHelpers.Windows.cs b/src/Files.App/Utils/Storage/Helpers/MtpHelpers.Windows.cs deleted file mode 100644 index ddc5d1f16a17..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/MtpHelpers.Windows.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Files Community -// SPDX-License-Identifier: MPL-2.0 - -using System.Collections.Concurrent; -using System.IO; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; - -namespace Files.App.Utils.Storage -{ - public static class MtpHelpers - { - private static readonly ConcurrentDictionary _deviceParsingNames = new(StringComparer.OrdinalIgnoreCase); - - /// - /// Resolves a \\?\DeviceName\path to a shell Portable Devices namespace path - /// so that shell APIs like work correctly. - /// - public static string? ResolveMtpShellPath(string mtpPath) - { - var withoutPrefix = mtpPath.AsSpan(4); - var sep = withoutPrefix.IndexOf('\\'); - var deviceName = (sep >= 0 ? withoutPrefix[..sep] : withoutPrefix).ToString(); - - if (!_deviceParsingNames.TryGetValue(deviceName, out var parsingName)) - { - unsafe - { - _deviceParsingNames[deviceName] = parsingName = FindDeviceParsingName(deviceName); - } - } - - return parsingName is null ? null - : sep >= 0 ? Path.Combine(parsingName, withoutPrefix[(sep + 1)..].ToString()) - : parsingName; - } - - private unsafe static string? FindDeviceParsingName(string deviceName) - { - HRESULT hr = PInvoke.SHGetKnownFolderItem(FOLDERID.FOLDERID_ComputerFolder, KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, null, out IShellItem computerFolderItem); - if (hr.ThrowIfFailedOnDebug().Failed) - return null; - - hr = computerFolderItem.BindToHandler(null, PInvoke.BHID_EnumItems, out IEnumShellItems? pEnum); - if (hr.ThrowIfFailedOnDebug().Failed || pEnum is null) - return null; - - IShellItem[] children = new IShellItem[1]; - while (true) - { - if (pEnum.Next(children) != HRESULT.S_OK) - break; - - IShellItem pChild = children[0]; - - pChild.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY, out var szName); - var name = szName.ToString(); - PInvoke.CoTaskMemFree(szName.Value); - - if (name is null || !deviceName.StartsWith(name, StringComparison.OrdinalIgnoreCase)) - continue; - - pChild.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var szParsing); - var result = szParsing.ToString(); - PInvoke.CoTaskMemFree(szParsing.Value); - return result; - } - - return null; - } - } -} diff --git a/src/Files.App/Utils/Storage/Helpers/StorableWithPath.cs b/src/Files.App/Utils/Storage/Helpers/StorableWithPath.cs index 68503787eaab..e382100d959d 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorableWithPath.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorableWithPath.cs @@ -27,9 +27,6 @@ public sealed record StorableWithPath : IStorageItemWithPath /// public string Name => Storable?.Name ?? IO.Path.GetFileName(IO.Path.TrimEndingDirectorySeparator(Path)); -#if WINDOWS - IStorageItem? IStorageItemWithPath.Item => null; -#endif /// /// Initializes a new instance of the record. diff --git a/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Linux.cs b/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Linux.cs index ee289c28dcdc..8711f7d0a228 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Linux.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using System.IO; using Windows.Storage; @@ -91,4 +90,3 @@ public static Task> GetFoldersWithPathAsync(this St => throw new NotSupportedException("Use IFolder.GetItemsAsync instead of the legacy WinRT storage layer."); } } -#endif diff --git a/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Windows.cs b/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Windows.cs deleted file mode 100644 index e430fe26d8a1..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.Windows.cs +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using Windows.Storage; -using Windows.Storage.Search; -using WinRT; - -namespace Files.App.Utils.Storage -{ - public static partial class StorageFileExtensions - { - [DynamicWindowsRuntimeCast(typeof(StorageFile))] - public static BaseStorageFile? AsBaseStorageFile(this IStorageItem? item) - { - if (item is null || !item.IsOfType(StorageItemTypes.File)) - return null; - - return item is StorageFile file ? new SystemStorageFile(file) : item as BaseStorageFile; - } - - public static async Task> ToStandardStorageItemsAsync(this IEnumerable items) - { - var newItems = new List(); - foreach (var item in items) - { - try - { - if (item is null) - { - } - else if (item.IsOfType(StorageItemTypes.File)) - { - newItems.Add(await item.AsBaseStorageFile()!.ToStorageFileAsync()); - } - else if (item.IsOfType(StorageItemTypes.Folder)) - { - newItems.Add(await item.AsBaseStorageFolder()!.ToStorageFolderAsync()); - } - } - catch (NotSupportedException) - { - // Ignore items that can't be converted - } - } - return newItems; - } - - [DynamicWindowsRuntimeCast(typeof(StorageFolder))] - public static BaseStorageFolder? AsBaseStorageFolder(this IStorageItem? item) - { - if (item is not null && item.IsOfType(StorageItemTypes.Folder)) - return item is StorageFolder folder ? new SystemStorageFolder(folder) : item as BaseStorageFolder; - - return null; - } - - public async static Task DangerousGetFileFromPathAsync - (string value, StorageFolderWithPath? rootFolder = null, StorageFolderWithPath? parentFolder = null) - => (await DangerousGetFileWithPathFromPathAsync(value, rootFolder, parentFolder)).Item; - public async static Task DangerousGetFileWithPathFromPathAsync - (string value, StorageFolderWithPath? rootFolder = null, StorageFolderWithPath? parentFolder = null) - { - if (rootFolder is not null) - { - var rootItem = rootFolder.Item!; - var currComponents = GetDirectoryPathComponents(value); - - if (parentFolder is not null && value.IsSubPathOf(parentFolder.Path)) - { - var folder = parentFolder.Item!; - var prevComponents = GetDirectoryPathComponents(parentFolder.Path); - var path = parentFolder.Path; - foreach (var component in currComponents.ExceptBy(prevComponents, c => c.Path).SkipLast(1)) - { - folder = await folder.GetFolderAsync(component.Title ?? throw new InvalidOperationException("A path component is missing its title.")); - path = PathNormalization.Combine(path, folder.Name); - } - var file = await folder.GetFileAsync(currComponents.Last().Title ?? throw new InvalidOperationException("A path component is missing its title.")); - path = PathNormalization.Combine(path, file.Name); - return new StorageFileWithPath(file, path); - } - else if (value.IsSubPathOf(rootFolder.Path)) - { - var folder = rootItem; - var path = rootFolder.Path; - foreach (var component in currComponents.Skip(1).SkipLast(1)) - { - folder = await folder.GetFolderAsync(component.Title ?? throw new InvalidOperationException("A path component is missing its title.")); - path = PathNormalization.Combine(path, folder.Name); - } - var file = await folder.GetFileAsync(currComponents.Last().Title ?? throw new InvalidOperationException("A path component is missing its title.")); - path = PathNormalization.Combine(path, file.Name); - return new StorageFileWithPath(file, path); - } - } - - var fullPath = (parentFolder is not null && !FtpHelpers.IsFtpPath(value) && !Path.IsPathRooted(value) && !ShellStorageFolder.IsShellPath(value)) // "::{" not a valid root - ? Path.GetFullPath(Path.Combine(parentFolder.Path, value)) // Relative path - : value; - var item = await BaseStorageFile.GetFileFromPathAsync(fullPath); - - if (parentFolder is not null && parentFolder.Item is IPasswordProtectedItem ppis && item is IPasswordProtectedItem ppid) - ppid.Credentials = ppis.Credentials; - - return new StorageFileWithPath(item); - } - public async static Task> GetFilesWithPathAsync - (this StorageFolderWithPath parentFolder, uint maxNumberOfItems = uint.MaxValue) - => (await parentFolder.Item!.GetFilesAsync(CommonFileQuery.DefaultQuery, 0, maxNumberOfItems)) - .Select(x => new StorageFileWithPath(x, string.IsNullOrEmpty(x.Path) ? PathNormalization.Combine(parentFolder.Path, x.Name) : x.Path)).ToList(); - - public async static Task DangerousGetFolderFromPathAsync - (string value, StorageFolderWithPath? rootFolder = null, StorageFolderWithPath? parentFolder = null) - => (await DangerousGetFolderWithPathFromPathAsync(value, rootFolder, parentFolder)).Item; - public async static Task DangerousGetFolderWithPathFromPathAsync - (string value, StorageFolderWithPath? rootFolder = null, StorageFolderWithPath? parentFolder = null) - { - // Archive paths can't be resolved by chaining WinRT GetFolderAsync from a network root/parent - // (an archive is not a real subfolder of the share); resolve them directly like local archives. - if (rootFolder is not null && !ZipStorageFolder.IsZipPath(value)) - { - var rootItem = rootFolder.Item!; - var currComponents = GetDirectoryPathComponents(value); - - if (rootFolder.Path == value) - { - return rootFolder; - } - else if (parentFolder is not null && value.IsSubPathOf(parentFolder.Path)) - { - var folder = parentFolder.Item!; - var prevComponents = GetDirectoryPathComponents(parentFolder.Path); - var path = parentFolder.Path; - foreach (var component in currComponents.ExceptBy(prevComponents, c => c.Path)) - { - folder = await folder.GetFolderAsync(component.Title ?? throw new InvalidOperationException("A path component is missing its title.")); - path = PathNormalization.Combine(path, folder.Name); - } - return new StorageFolderWithPath(folder, path); - } - else if (value.IsSubPathOf(rootFolder.Path)) - { - var folder = rootItem; - var path = rootFolder.Path; - foreach (var component in currComponents.Skip(1)) - { - folder = await folder.GetFolderAsync(component.Title ?? throw new InvalidOperationException("A path component is missing its title.")); - path = PathNormalization.Combine(path, folder.Name); - } - return new StorageFolderWithPath(folder, path); - } - } - - var fullPath = (parentFolder is not null && !FtpHelpers.IsFtpPath(value) && !Path.IsPathRooted(value) && !ShellStorageFolder.IsShellPath(value)) // "::{" not a valid root - ? Path.GetFullPath(Path.Combine(parentFolder.Path, value)) // Relative path - : value; - var item = await BaseStorageFolder.GetFolderFromPathAsync(fullPath); - - if (parentFolder is not null && parentFolder.Item is IPasswordProtectedItem ppis && item is IPasswordProtectedItem ppid) - ppid.Credentials = ppis.Credentials; - - return new StorageFolderWithPath(item); - } - public async static Task> GetFoldersWithPathAsync - (this StorageFolderWithPath parentFolder, uint maxNumberOfItems = uint.MaxValue) - => (await parentFolder.Item!.GetFoldersAsync(CommonFolderQuery.DefaultQuery, 0, maxNumberOfItems)) - .Select(x => new StorageFolderWithPath(x, string.IsNullOrEmpty(x.Path) ? PathNormalization.Combine(parentFolder.Path, x.Name) : x.Path)).ToList(); - public async static Task?> GetFoldersWithPathAsync - (this StorageFolderWithPath parentFolder, string nameFilter, uint maxNumberOfItems = uint.MaxValue) - { - if (parentFolder is null) - return null; - - var folder = parentFolder.Item!; - - var queryOptions = new QueryOptions - { - ApplicationSearchFilter = $"System.FileName:{nameFilter}*" - }; - BaseStorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(queryOptions); - - return (await queryResult.GetFoldersAsync(0, maxNumberOfItems)) - .Select(x => new StorageFolderWithPath(x, string.IsNullOrEmpty(x.Path) ? PathNormalization.Combine(parentFolder.Path, x.Name) : x.Path)).ToList(); - } - - } -} diff --git a/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.cs b/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.cs index 3956695ee652..4e865e54d420 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageFileExtensions.cs @@ -95,7 +95,6 @@ public static List GetDirectoryPathComponents(string value) { List pathBoxItems = []; -#if !WINDOWS // trash:/// is a single virtual location, not a directory chain if (value.StartsWith(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.Ordinal)) return [GetPathItem(Constants.UserEnvironmentPaths.RecycleBinPath, Constants.UserEnvironmentPaths.RecycleBinPath)]; @@ -103,7 +102,6 @@ public static List GetDirectoryPathComponents(string value) // POSIX paths start at the root directory, which the separator scan below would skip if (value.StartsWith('/')) pathBoxItems.Add(new PathBoxItem() { Title = "/", Path = "/", ChevronToolTip = string.Format(Strings.BreadcrumbBarChevronButtonToolTip.GetLocalizedResource(), "/") }); -#endif if (value.Contains('/', StringComparison.Ordinal)) { @@ -157,19 +155,11 @@ public static async Task> GetDirectoryPathComponentsWithDispla } else { -#if WINDOWS - var path = item.Path!; - BaseStorageFolder? folder = await FilesystemTasks.WrapNullable(() => DangerousGetFolderFromPathAsync(path)); - - if (!string.IsNullOrEmpty(folder?.DisplayName)) - item.Title = folder.DisplayName; -#else var path = item.Path!; var folder = (await StorageHelpers.GetFolderAsync(path)).Result; if (!string.IsNullOrEmpty(folder?.Name)) item.Title = folder.Name; -#endif } item.ChevronToolTip = string.Format(Strings.BreadcrumbBarChevronButtonToolTip.GetLocalizedResource(), item.Title); @@ -251,10 +241,6 @@ private static string ResolvePath(string path, bool isFtp) if (path.StartsWith("Settings")) return "Settings"; -#if WINDOWS - if (ShellStorageFolder.IsShellPath(path)) - return ShellHelpers.ResolveShellPath(path); -#endif var pathBuilder = new StringBuilder(path); var lastPathIndex = path.Length - 1; diff --git a/src/Files.App/Utils/Storage/Helpers/StorageFileWithPath.cs b/src/Files.App/Utils/Storage/Helpers/StorageFileWithPath.cs index 43fdebec4377..eccaa8bac46e 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageFileWithPath.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageFileWithPath.cs @@ -11,9 +11,6 @@ public sealed class StorageFileWithPath : IStorageItemWithPath public string Path { get; } public string Name => Item?.Name ?? IO.Path.GetFileName(Path)!; -#if WINDOWS - IStorageItem? IStorageItemWithPath.Item => Item; -#endif public BaseStorageFile? Item { get; } public FilesystemItemType ItemType => FilesystemItemType.File; diff --git a/src/Files.App/Utils/Storage/Helpers/StorageFolderWithPath.cs b/src/Files.App/Utils/Storage/Helpers/StorageFolderWithPath.cs index ee8e81b08ac5..a87575ae32ca 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageFolderWithPath.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageFolderWithPath.cs @@ -11,9 +11,6 @@ public sealed class StorageFolderWithPath : IStorageItemWithPath public string Path { get; } public string Name => Item?.Name ?? IO.Path.GetFileName(Path)!; -#if WINDOWS - IStorageItem? IStorageItemWithPath.Item => Item; -#endif public BaseStorageFolder? Item { get; } public FilesystemItemType ItemType => FilesystemItemType.Directory; diff --git a/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Storables.cs b/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Storables.cs index 1ec0416f9fb4..b3facc2df870 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Storables.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Storables.cs @@ -42,11 +42,7 @@ public static async Task> ToStorableResult(this ISto /// Gets whether the item is a member of an archive; such items can only be copied out. /// public static bool IsArchiveMember(this IStorageItemWithPath item) -#if WINDOWS - => item.Item is ZipStorageFile || item.Item is ZipStorageFolder; -#else => item.Storable is Files.App.Storage.Archives.ArchiveEntryFile or Files.App.Storage.Archives.ArchiveFolder || Files.Shared.Helpers.FileExtensionHelpers.IsZipPath(item.Path, includeRoot: false); -#endif } } diff --git a/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Windows.cs b/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Windows.cs deleted file mode 100644 index 2db99bf26d57..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/StorageHelpers.Windows.cs +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using System.Runtime.InteropServices; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; - -namespace Files.App.Helpers -{ - /// - /// related Helpers - /// - public static partial class StorageHelpers - { - public static async Task ToStorageItem(this IStorageItemWithPath item) - { - return (await item.ToStorageItemResult()).Result; - } - - public static async Task ToStorageItem(string path) where TRequested : IStorageItem - { - FilesystemResult? file = null; - FilesystemResult? folder = null; - - if (FileExtensionHelpers.IsShortcutOrUrlFile(path)) - { - // TODO: In the future, when IStorageItemWithPath will inherit from IStorageItem, - // we could implement this code here for getting .lnk files - // for now, we can't - return default; - } - - // Fast get attributes -#if WINDOWS - uint itemAttributes = PInvoke.GetFileAttributes(path); - bool exists = itemAttributes != PInvoke.INVALID_FILE_ATTRIBUTES; - bool isDirectory = exists && (itemAttributes & (uint)FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_DIRECTORY) != 0; -#else - bool isDirectory = System.IO.Directory.Exists(path); - bool exists = isDirectory || System.IO.File.Exists(path); -#endif - if (exists) // Exists on local storage - { - // Directory - if (isDirectory) - { - if (typeof(IStorageFile).IsAssignableFrom(typeof(TRequested))) // Wanted file - { - // NotAFile - return default; - } - else // Just get the directory - { - await GetFolderAsync(); - } - } - else // File - { - if (typeof(IStorageFolder).IsAssignableFrom(typeof(TRequested))) // Wanted directory - { - // NotAFile - return default; - } - else // Just get the file - { - await GetFileAsync(); - } - } - } - else // Does not exist or is not present on local storage - { - Debug.WriteLine($"Path does not exist. Trying to find storage item manually (HRESULT: {Marshal.GetLastWin32Error()})"); - - if (typeof(IStorageFile).IsAssignableFrom(typeof(TRequested))) - { - await GetFileAsync(); - } - else if (typeof(IStorageFolder).IsAssignableFrom(typeof(TRequested))) - { - await GetFolderAsync(); - } - else if (typeof(IStorageItem).IsAssignableFrom(typeof(TRequested))) - { - if (System.IO.Path.HasExtension(path)) // Possibly a file - { - await GetFileAsync(); - } - - if (file?.Result is null) // Possibly a folder - { - await GetFolderAsync(); - - if (file is null && folder?.Result is null) - { - // Try file because it wasn't checked - await GetFileAsync(); - } - } - } - } - - if (file?.Result is TRequested requestedFile) - { - return requestedFile; - } - else if (folder?.Result is TRequested requestedFolder) - { - return requestedFolder; - } - - return default; - - // Extensions - - async Task GetFileAsync() - { - var rootItem = await FilesystemTasks.WrapNullable(() => DriveHelpers.GetRootFromPathAsync(path)); - file = await FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFileFromPathAsync(path, rootItem.Result)); - } - - async Task GetFolderAsync() - { - var rootItem = await FilesystemTasks.WrapNullable(() => DriveHelpers.GetRootFromPathAsync(path)); - folder = await FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, rootItem.Result)); - } - } - - public static async Task GetFileSize(this IStorageFile file) - { - BasicProperties properties = await file.GetBasicPropertiesAsync(); - return (long)properties.Size; - } - - public static async Task> ToStorageItemResult(this IStorageItemWithPath item) - { - var returnedItem = new FilesystemResult(null, FileSystemStatusCode.Generic); - var rootItem = await FilesystemTasks.WrapNullable(() => DriveHelpers.GetRootFromPathAsync(item.Path)); - if (!string.IsNullOrEmpty(item.Path)) - { - returnedItem = (item.ItemType == FilesystemItemType.File) ? - ToType( - await FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFileFromPathAsync(item.Path, rootItem))) : - ToType( - await FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(item.Path, rootItem))); - } - if (returnedItem.Result is null && item.Item is not null) - returnedItem = new FilesystemResult(item.Item, FileSystemStatusCode.Success); - if (returnedItem.Result is IPasswordProtectedItem ppid && item.Item is IPasswordProtectedItem ppis) - ppid.Credentials = ppis.Credentials; - return returnedItem; - } - - public static IStorageItemWithPath FromPathAndType(string customPath, FilesystemItemType? itemType) - { - return (itemType == FilesystemItemType.File) ? - new StorageFileWithPath(null, customPath) : - new StorageFolderWithPath(null, customPath); - } - - public static async Task GetTypeFromPath(string path) - { - IStorageItem? item = await ToStorageItem(path); - - return item is null ? FilesystemItemType.File : (item.IsOfType(StorageItemTypes.Folder) ? FilesystemItemType.Directory : FilesystemItemType.File); - } - - public static bool Exists(string path) - { - if (OperatingSystem.IsLinux()) - return System.IO.Directory.Exists(path) || System.IO.File.Exists(path); - - return PInvoke.GetFileAttributes(path) != PInvoke.INVALID_FILE_ATTRIBUTES; - } - - public static IStorageItemWithPath? FromStorageItem(this IStorageItem? item, string? customPath = null, FilesystemItemType? itemType = null) - { - if (item is null) - { - return FromPathAndType(customPath - ?? throw new InvalidOperationException("A path is required when converting a missing storage item."), itemType); - } - else if (item.IsOfType(StorageItemTypes.File)) - { - return new StorageFileWithPath(item.AsBaseStorageFile(), GetPath(item, customPath)); - } - else if (item.IsOfType(StorageItemTypes.Folder)) - { - return new StorageFolderWithPath(item.AsBaseStorageFolder(), GetPath(item, customPath)); - } - return null; - - static string GetPath(IStorageItem item, string? customPath) - => !string.IsNullOrEmpty(item.Path) - ? item.Path - : customPath ?? string.Empty; - } - - public static FilesystemResult ToType(FilesystemResult result) where T : class - { - return new FilesystemResult(result.Result as T, result.ErrorCode); - } - } -} diff --git a/src/Files.App/Utils/Storage/Helpers/StorageHelpers.cs b/src/Files.App/Utils/Storage/Helpers/StorageHelpers.cs index 00205c1eb116..08face5831b7 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageHelpers.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageHelpers.cs @@ -8,7 +8,6 @@ namespace Files.App.Helpers { public static partial class StorageHelpers { -#if !WINDOWS // LINUX-TODO(storage): remove the remaining WinRT entry points (ToStorageItem, FromStorageItem) once their callers use storables. public static async Task ToStorageItem(string path) where TRequested : IStorageItem { @@ -35,6 +34,5 @@ public static bool Exists(string path) => FromPathAndType(!string.IsNullOrEmpty(item?.Path) ? item.Path : customPath ?? throw new InvalidOperationException("A path is required when converting a missing storage item."), item is null ? itemType : item.IsOfType(StorageItemTypes.Folder) ? FilesystemItemType.Directory : FilesystemItemType.File); -#endif } } diff --git a/src/Files.App/Utils/Storage/Helpers/StorageSenseHelper.cs b/src/Files.App/Utils/Storage/Helpers/StorageSenseHelper.cs index 4cfb2f63dc16..d19a7f4e8034 100644 --- a/src/Files.App/Utils/Storage/Helpers/StorageSenseHelper.cs +++ b/src/Files.App/Utils/Storage/Helpers/StorageSenseHelper.cs @@ -10,20 +10,8 @@ internal sealed class StorageSenseHelper { public static async Task OpenStorageSenseAsync(string path) { -#if !WINDOWS // LINUX-TODO(storage-sense): no system storage cleanup page to open await Task.CompletedTask; -#else - if (!path.StartsWith(Constants.UserEnvironmentPaths.SystemDrivePath, StringComparison.OrdinalIgnoreCase) - && ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - { - LaunchHelper.LaunchSettings("page=SettingsPageStorageSenseStorageOverview&target=SystemSettings_StorageSense_VolumeListLink"); - } - else - { - await Launcher.LaunchUriAsync(new Uri("ms-settings:storagesense")); - } -#endif } } } diff --git a/src/Files.App/Utils/Storage/Helpers/SyncRootHelpers.Windows.cs b/src/Files.App/Utils/Storage/Helpers/SyncRootHelpers.Windows.cs deleted file mode 100644 index 3f58d9be282e..000000000000 --- a/src/Files.App/Utils/Storage/Helpers/SyncRootHelpers.Windows.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Win32; -using Windows.Win32; -using Windows.Win32.System.Com; -using Windows.Win32.System.WinRT; - -namespace Files.App.Utils.Storage -{ - internal static class SyncRootHelpers - { - private static (bool Success, ulong Capacity, ulong Used) GetSyncRootQuotaFromSyncRootId(string syncRootId) - { - using var key = Registry.LocalMachine.OpenSubKey($"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\SyncRootManager\\{syncRootId}"); - if (key?.GetValue("StorageProviderStatusUISourceFactory") is not string factoryClsidString || - !Guid.TryParse(factoryClsidString, out var factoryClsid)) - return (false, 0, 0); - - ulong ulTotalSize = 0ul, ulUsedSize = 0ul; - - if (PInvoke.CoCreateInstance(factoryClsid, null, CLSCTX.CLSCTX_LOCAL_SERVER, out IStorageProviderStatusUISourceFactory? pStorageProviderStatusUISourceFactory).ThrowIfFailedOnDebug().Failed || - pStorageProviderStatusUISourceFactory is null) - return (false, 0, 0); - - if (pStorageProviderStatusUISourceFactory.GetStatusUISource(syncRootId, out IStorageProviderStatusUISource pStorageProviderStatusUISource).ThrowIfFailedOnDebug().Failed || - pStorageProviderStatusUISource.GetStatusUI(out IStorageProviderStatusUI pStorageProviderStatusUI).ThrowIfFailedOnDebug().Failed || - pStorageProviderStatusUI.GetQuotaUI(out IStorageProviderQuotaUI pStorageProviderQuotaUI).ThrowIfFailedOnDebug().Failed || - pStorageProviderQuotaUI.GetQuotaTotalInBytes(out ulTotalSize).ThrowIfFailedOnDebug().Failed || - pStorageProviderQuotaUI.GetQuotaUsedInBytes(out ulUsedSize).ThrowIfFailedOnDebug().Failed) - return (false, 0, 0); - - return (true, ulTotalSize, ulUsedSize); - } - - public static async Task<(bool Success, ulong Capacity, ulong Used)> GetSyncRootQuotaAsync(string path) - { - Windows.Storage.StorageFolder folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(path); - Windows.Storage.Provider.StorageProviderSyncRootInfo? syncRootInfo = null; - - try - { - syncRootInfo = Windows.Storage.Provider.StorageProviderSyncRootManager.GetSyncRootInformationForFolder(folder); - } - catch - { - return (false, 0, 0); - } - - if (syncRootInfo is null || syncRootInfo.Id is null) - { - return (false, 0, 0); - } - - return GetSyncRootQuotaFromSyncRootId(syncRootInfo.Id); - } - } -} diff --git a/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs b/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs index 998837b8efd7..a6be91a606c2 100644 --- a/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs +++ b/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs @@ -31,13 +31,7 @@ public async Task Undo(IStorageHistory history) var helpers = this.helpers ?? throw new ObjectDisposedException(nameof(StorageHistoryOperations)); var operations = this.operations ?? throw new ObjectDisposedException(nameof(StorageHistoryOperations)); ReturnResult returnStatus = ReturnResult.InProgress; -#if WINDOWS - Progress progress = new(); - - progress.ProgressChanged += (s, e) => returnStatus = e.Status!.Value.ToStatus(); -#else HistoryProgress progress = new(); -#endif switch (history.OperationType) { @@ -64,13 +58,9 @@ public async Task Undo(IStorageHistory history) for (int i = 0; i < renamedItems.Count; i++) { string name = Path.GetFileName(history.Source[i].Path); -#if WINDOWS - await operations.RenameAsync(renamedItems[i], name, collision, progress, cancellationToken); -#else var replayed = await operations.RenameAsync(renamedItems[i], name, collision, progress, cancellationToken); if (replayed?.Destination is { Count: > 0 }) history.Source[i] = replayed.Destination[0]; -#endif } } break; @@ -86,11 +76,7 @@ public async Task Undo(IStorageHistory history) var movedItems = history.Destination; if (!IsHistoryNull(history.Source) && !IsHistoryNull(movedItems)) { -#if WINDOWS - return await helpers.MoveItemsAsync(movedItems, history.Source.Select(item => item.Path), false, false); -#else return await helpers.MoveItemsAsync(movedItems, history.Source.Select(item => item.Path), false, false, replayed => UpdateHistory(history, replayed, true)); -#endif } break; case FileOperationType.Extract: // Opposite: No opposite for archive extraction @@ -101,11 +87,7 @@ public async Task Undo(IStorageHistory history) var recycledItems = history.Destination; if (!IsHistoryNull(history.Source) && !IsHistoryNull(recycledItems)) { -#if WINDOWS - returnStatus = await helpers.RestoreItemsFromTrashAsync(recycledItems, history.Source.Select(item => item.Path), false); -#else returnStatus = await helpers.RestoreItemsFromTrashAsync(recycledItems, history.Source.Select(item => item.Path), false, replayed => UpdateHistory(history, replayed, true)); -#endif if (returnStatus is ReturnResult.IntegrityCheckFailed) // Not found, corrupted { App.HistoryWrapper.RemoveHistory(history, false); @@ -124,11 +106,7 @@ public async Task Undo(IStorageHistory history) else { // We need to change the recycled item paths (since IDs are different) - for Redo() to work -#if WINDOWS - App.HistoryWrapper.ModifyCurrentHistory(newHistory); -#else UpdateHistory(history, newHistory, true); -#endif } } break; @@ -137,11 +115,7 @@ public async Task Undo(IStorageHistory history) break; } -#if WINDOWS - return returnStatus; -#else return progress.Status ?? returnStatus; -#endif } public async Task Redo(IStorageHistory history) @@ -149,13 +123,7 @@ public async Task Redo(IStorageHistory history) var helpers = this.helpers ?? throw new ObjectDisposedException(nameof(StorageHistoryOperations)); var operations = this.operations ?? throw new ObjectDisposedException(nameof(StorageHistoryOperations)); ReturnResult returnStatus = ReturnResult.InProgress; -#if WINDOWS - Progress progress = new(); - - progress.ProgressChanged += (s, e) => { returnStatus = e.Status!.Value.ToStatus(); }; -#else HistoryProgress progress = new(); -#endif switch (history.OperationType) { @@ -177,13 +145,9 @@ await operations.CreateShortcutItemsAsync(history.Source, for (int i = 0; i < history.Source.Count; i++) { string name = Path.GetFileName(renameDestinations[i].Path); -#if WINDOWS - await operations.RenameAsync(history.Source[i], name, collision, progress, cancellationToken); -#else var replayed = await operations.RenameAsync(history.Source[i], name, collision, progress, cancellationToken); if (replayed?.Destination is { Count: > 0 }) renameDestinations[i] = replayed.Destination[0]; -#endif } } break; @@ -191,22 +155,14 @@ await operations.CreateShortcutItemsAsync(history.Source, var copyDestinations = history.Destination; if (!IsHistoryNull(history.Source) && !IsHistoryNull(copyDestinations)) { -#if WINDOWS - return await helpers.CopyItemsAsync(history.Source, copyDestinations.Select(item => item.Path), false, false); -#else return await helpers.CopyItemsAsync(history.Source, copyDestinations.Select(item => item.Path), false, false, replayed => UpdateHistory(history, replayed, false)); -#endif } break; case FileOperationType.Move: var moveDestinations = history.Destination; if (!IsHistoryNull(history.Source) && !IsHistoryNull(moveDestinations)) { -#if WINDOWS - return await helpers.MoveItemsAsync(history.Source, moveDestinations.Select(item => item.Path), false, false); -#else return await helpers.MoveItemsAsync(history.Source, moveDestinations.Select(item => item.Path), false, false, replayed => UpdateHistory(history, replayed, false)); -#endif } break; case FileOperationType.Extract: @@ -233,11 +189,7 @@ await operations.CreateShortcutItemsAsync(history.Source, var restoreDestinations = history.Destination; if (!IsHistoryNull(history.Source) && !IsHistoryNull(restoreDestinations)) { -#if WINDOWS - await helpers.RestoreItemsFromTrashAsync(history.Source, restoreDestinations.Select(item => item.Path), false); -#else return await helpers.RestoreItemsFromTrashAsync(history.Source, restoreDestinations.Select(item => item.Path), false, replayed => UpdateHistory(history, replayed, false)); -#endif } break; case FileOperationType.Delete: @@ -245,11 +197,7 @@ await operations.CreateShortcutItemsAsync(history.Source, break; } -#if WINDOWS - return returnStatus; -#else return progress.Status ?? returnStatus; -#endif } public void Dispose() @@ -261,7 +209,6 @@ public void Dispose() operations = null; } -#if !WINDOWS private static void UpdateHistory(IStorageHistory history, IStorageHistory? replayed, bool reverse) { if (replayed?.Destination is not null) @@ -279,7 +226,6 @@ private sealed class HistoryProgress : IProgress public void Report(StatusCenterItemProgressModel value) => model = value; } -#endif private static bool IsHistoryNull([NotNullWhen(false)] IEnumerable? source) => source is null || !source.All(HasPath); diff --git a/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Linux.cs b/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Linux.cs index 634f7b0428b1..40eb124b9817 100644 --- a/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Linux.cs +++ b/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Trash; using Windows.ApplicationModel.DataTransfer; @@ -54,4 +53,3 @@ public static void WaitForCompletion() } } } -#endif diff --git a/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Windows.cs b/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Windows.cs deleted file mode 100644 index 7ca8658d6713..000000000000 --- a/src/Files.App/Utils/Storage/Operations/FileOperationsHelpers.Windows.cs +++ /dev/null @@ -1,1158 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Utils.Storage.Operations; -using Files.Shared.Helpers; -using Microsoft.Extensions.Logging; -using System.Collections.Concurrent; -using System.IO; -using Windows.ApplicationModel.DataTransfer; -using Windows.Win32; -using Windows.Win32.UI.WindowsAndMessaging; -using FILEOPERATION_FLAGS = Windows.Win32.UI.Shell.FILEOPERATION_FLAGS; -using HRESULT = Windows.Win32.Foundation.HRESULT; -using HWND = Windows.Win32.Foundation.HWND; -using PROPERTYKEY = Windows.Win32.Foundation.PROPERTYKEY; -using SLR_FLAGS = Windows.Win32.UI.Shell.SLR_FLAGS; - -namespace Files.App.Utils.Storage -{ - public sealed partial class FileOperationsHelpers - { - private static readonly PROPERTYKEY PKEY_FilePlaceholderStatus = new() { fmtid = new("B2F9B9D6-FEC4-4DD5-94D7-8957488C807B"), pid = 2 }; - private const uint PS_CLOUDFILE_PLACEHOLDER = 8; - - private static ProgressHandler? progressHandler; // Warning: must be initialized from a MTA thread - - public static Task SetClipboard(string[] filesToCopy, DataPackageOperation operation) - { - return STATask.Run(() => - { - uint preferredDropEffect = (uint)(operation == DataPackageOperation.Copy - ? DataPackageOperation.Copy | DataPackageOperation.Link - : DataPackageOperation.Move); - ShellDataObject.SetClipboard(filesToCopy, preferredDropEffect); - }, App.Logger); - } - - public static Task<(bool, ShellOperationResult)> CreateItemAsync(string filePath, string fileOp, long ownerHwnd, bool asAdmin, string? template = null, byte[]? dataBytes = null) - { - return STATask.Run(async () => - { - using var op = new ShellFileOperations2(); - - op.Options = FILEOPERATION_FLAGS.FOF_SILENT | FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR | FILEOPERATION_FLAGS.FOF_RENAMEONCOLLISION | FILEOPERATION_FLAGS.FOF_NOERRORUI; - if (asAdmin) - { - op.Options |= FILEOPERATION_FLAGS.FOFX_SHOWELEVATIONPROMPT | FILEOPERATION_FLAGS.FOFX_REQUIREELEVATION; - } - op.OwnerWindow = (HWND)(nint)ownerHwnd; - - var shellOperationResult = new ShellOperationResult(); - var parentPath = Path.GetDirectoryName(filePath); - - if (parentPath is null || !SafetyExtensions.IgnoreExceptions(() => - { - using var shd = new ShellFolder(parentPath); - op.QueueNewItemOperation(shd, Path.GetFileName(filePath), - fileOp == "CreateFolder" ? FileAttributes.Directory : FileAttributes.Normal, template); - })) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Destination = filePath, - HResult = -1 - }); - } - - var createTcs = new TaskCompletionSource(); - op.PostNewItem += (s, e) => - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = e.Result.Succeeded, - Destination = e.DestItem.GetParsingPath(), - HResult = (int)e.Result - }); - }; - op.FinishOperations += (s, e) => createTcs.TrySetResult(e.Result.Succeeded); - - try - { - op.PerformOperations(); - } - catch - { - createTcs.TrySetResult(false); - } - - if (dataBytes is not null && - shellOperationResult.Items.SingleOrDefault() is { Succeeded: true, Destination: { } destination }) - { - SafetyExtensions.IgnoreExceptions(() => - { - using var fs = new FileStream(destination, FileMode.Open); - fs.Write(dataBytes, 0, dataBytes.Length); - fs.Flush(); - }, App.Logger); - } - - return (await createTcs.Task, shellOperationResult); - }, App.Logger); - } - - public static Task<(bool, ShellOperationResult)> TestRecycleAsync(string[] fileToDeletePath) - { - return STATask.Run(async () => - { - using var op = new ShellFileOperations2(); - - op.Options = FILEOPERATION_FLAGS.FOF_SILENT | FILEOPERATION_FLAGS.FOF_NOCONFIRMATION | FILEOPERATION_FLAGS.FOF_NOERRORUI; - op.Options |= FILEOPERATION_FLAGS.FOFX_RECYCLEONDELETE; - - var shellOperationResult = new ShellOperationResult(); - var tryDelete = false; - - for (var i = 0; i < fileToDeletePath.Length; i++) - { - if (!SafetyExtensions.IgnoreExceptions(() => - { - using var shi = new ShellItem(fileToDeletePath[i]); - using var file = SafetyExtensions.IgnoreExceptions(() => GetFirstFile(shi)) ?? shi; - if (file.Properties.TryGetValue(PKEY_FilePlaceholderStatus, out var value) && value == PS_CLOUDFILE_PLACEHOLDER) - { - // Online only files cannot be tried for deletion, so they are treated as to be permanently deleted. - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = fileToDeletePath[i], - HResult = (int)HRESULT.COPYENGINE_E_RECYCLE_BIN_NOT_FOUND - }); - } - else - { - op.QueueDeleteOperation(file); - tryDelete = true; - } - })) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = fileToDeletePath[i], - HResult = -1 - }); - } - } - - if (!tryDelete) - return (true, shellOperationResult); - - var deleteTcs = new TaskCompletionSource(); - op.PreDeleteItem += [DebuggerHidden] (s, e) => - { - if ((e.Flags & Windows.Win32.UI.Shell._TRANSFER_SOURCE_FLAGS.TSF_DELETE_RECYCLE_IF_POSSIBLE) is 0) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = e.SourceItem.GetParsingPath(), - HResult = (int)HRESULT.COPYENGINE_E_RECYCLE_BIN_NOT_FOUND - }); - throw new Win32Exception((int)HRESULT.COPYENGINE_E_RECYCLE_BIN_NOT_FOUND); // E_FAIL, stops operation - } - else - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = true, - Source = e.SourceItem.GetParsingPath(), - HResult = (int)HRESULT.COPYENGINE_E_USER_CANCELLED - }); - throw new Win32Exception((int)HRESULT.COPYENGINE_E_USER_CANCELLED); // E_FAIL, stops operation - } - }; - op.FinishOperations += (s, e) => deleteTcs.TrySetResult(e.Result.Succeeded); - - try - { - op.PerformOperations(); - } - catch - { - deleteTcs.TrySetResult(false); - } - - return (await deleteTcs.Task, shellOperationResult); - }, App.Logger); - } - - public static Task<(bool, ShellOperationResult)> DeleteItemAsync(string[] fileToDeletePath, bool permanently, long ownerHwnd, bool asAdmin, IProgress? progress, string operationID = "") - { - operationID = string.IsNullOrEmpty(operationID) ? Guid.NewGuid().ToString() : operationID; - - StatusCenterItemProgressModel fsProgress = new( - progress, - false, - FileSystemStatusCode.InProgress); - - var cts = new CancellationTokenSource(); - var sizeCalculator = new FileSizeCalculator(fileToDeletePath); - - // Track the count and update the progress - sizeCalculator.ItemsCountChanged += (newCount) => - { - fsProgress.ItemsCount = newCount; - fsProgress.Report(); - }; - - var sizeTask = sizeCalculator.ComputeSizeAsync(cts.Token); - sizeTask.ContinueWith(_ => - { - fsProgress.TotalSize = 0; - fsProgress.ItemsCount = sizeCalculator.ItemsCount; - fsProgress.EnumerationCompleted = true; - fsProgress.Report(); - }); - - fsProgress.Report(); - progressHandler ??= new(); - - return STATask.Run(async () => - { - using var op = new ShellFileOperations2(); - - op.Options = FILEOPERATION_FLAGS.FOF_SILENT | FILEOPERATION_FLAGS.FOF_NOCONFIRMATION | FILEOPERATION_FLAGS.FOF_NOERRORUI; - - if (asAdmin) - { - op.Options |= FILEOPERATION_FLAGS.FOFX_SHOWELEVATIONPROMPT | FILEOPERATION_FLAGS.FOFX_REQUIREELEVATION; - } - - op.OwnerWindow = (HWND)(nint)ownerHwnd; - - if (!permanently) - { - op.Options |= FILEOPERATION_FLAGS.FOFX_RECYCLEONDELETE | FILEOPERATION_FLAGS.FOF_WANTNUKEWARNING; - } - - var shellOperationResult = new ShellOperationResult(); - - for (var i = 0; i < fileToDeletePath.Length; i++) - { - if (!SafetyExtensions.IgnoreExceptions(() => - { - using var shi = new ShellItem(fileToDeletePath[i]); - - op.QueueDeleteOperation(shi); - })) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = fileToDeletePath[i], - HResult = -1 - }); - } - } - - progressHandler.OwnerWindow = op.OwnerWindow; - progressHandler.AddOperation(operationID); - - var deleteTcs = new TaskCompletionSource(); - - // Right before deleting item - op.PreDeleteItem += (s, e) => - { - if (e.SourceItem is not { } sourceItem) - return; - - if (sourceItem.GetParsingPath() is { } sourcePath) - sizeCalculator.ForceComputeFileSize(sourcePath); - fsProgress.FileName = sourceItem.Name ?? string.Empty; - fsProgress.Report(); - }; - - // Right after deleted item - op.PostDeleteItem += (s, e) => - { - var sourceItem = e.SourceItem; - var sourcePath = sourceItem?.GetParsingPath(); - if (sourceItem is { IsFolder: false } && sourcePath is not null) - { - if (sizeCalculator.TryGetComputedFileSize(sourcePath, out _)) - fsProgress.AddProcessedItemsCount(1); - } - - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = e.Result.Succeeded, - Source = sourcePath, - Destination = e.DestItem?.GetParsingPath(), - HResult = (int)e.Result - }); - - UpdateFileTagsDb(e, "delete"); - }; - - op.FinishOperations += (s, e) - => deleteTcs.TrySetResult(e.Result.Succeeded); - - op.UpdateProgress += (s, e) => - { - // E_FAIL, stops operation - if (progressHandler.CheckCanceled(operationID)) - throw new Win32Exception(unchecked((int)0x80004005)); - - fsProgress.Report(e.ProgressPercentage); - progressHandler.UpdateOperation(operationID, e.ProgressPercentage); - }; - - try - { - op.PerformOperations(); - } - catch - { - deleteTcs.TrySetResult(false); - } - - progressHandler.RemoveOperation(operationID); - - cts.Cancel(); - - return (await deleteTcs.Task, shellOperationResult); - }, App.Logger); - } - - public static Task<(bool, ShellOperationResult)> RenameItemAsync(string fileToRenamePath, string newName, bool overwriteOnRename, long ownerHwnd, bool asAdmin, string operationID = "") - { - operationID = string.IsNullOrEmpty(operationID) ? Guid.NewGuid().ToString() : operationID; - - progressHandler ??= new(); - - return STATask.Run(async () => - { - using var op = new ShellFileOperations2(); - var shellOperationResult = new ShellOperationResult(); - - op.Options = FILEOPERATION_FLAGS.FOF_SILENT | FILEOPERATION_FLAGS.FOF_NOERRORUI; - if (asAdmin) - { - op.Options |= FILEOPERATION_FLAGS.FOFX_SHOWELEVATIONPROMPT | FILEOPERATION_FLAGS.FOFX_REQUIREELEVATION; - } - op.OwnerWindow = (HWND)(nint)ownerHwnd; - op.Options |= !overwriteOnRename ? FILEOPERATION_FLAGS.FOF_RENAMEONCOLLISION : 0; - - if (!SafetyExtensions.IgnoreExceptions(() => - { - using var shi = new ShellItem(fileToRenamePath); - op.QueueRenameOperation(shi, newName); - })) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = fileToRenamePath, - HResult = -1 - }); - } - - progressHandler.OwnerWindow = op.OwnerWindow; - progressHandler.AddOperation(operationID); - - var renameTcs = new TaskCompletionSource(); - op.PostRenameItem += (s, e) => - { - var sourcePath = e.SourceItem.GetParsingPath(); - var sourceFolderPath = sourcePath is null ? null : Path.GetDirectoryName(sourcePath); - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = e.Result.Succeeded, - Source = sourcePath, - Destination = sourceFolderPath is not null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(sourceFolderPath, e.Name) : null, - HResult = (int)e.Result - }); - }; - op.PostRenameItem += (_, e) => UpdateFileTagsDb(e, "rename"); - op.FinishOperations += (s, e) => renameTcs.TrySetResult(e.Result.Succeeded); - - try - { - op.PerformOperations(); - } - catch - { - renameTcs.TrySetResult(false); - } - - progressHandler.RemoveOperation(operationID); - - return (await renameTcs.Task, shellOperationResult); - }, App.Logger); - } - - public static Task<(bool, ShellOperationResult)> MoveItemAsync(string[] fileToMovePath, string[] moveDestination, bool overwriteOnMove, long ownerHwnd, bool asAdmin, IProgress progress, string operationID = "") - { - operationID = string.IsNullOrEmpty(operationID) ? Guid.NewGuid().ToString() : operationID; - - StatusCenterItemProgressModel fsProgress = new( - progress, - false, - FileSystemStatusCode.InProgress); - - var cts = new CancellationTokenSource(); - var sizeCalculator = new FileSizeCalculator(fileToMovePath); - - // Track the count and update the progress - sizeCalculator.ItemsCountChanged += (newCount) => - { - fsProgress.ItemsCount = newCount; - fsProgress.Report(); - }; - - var sizeTask = sizeCalculator.ComputeSizeAsync(cts.Token); - sizeTask.ContinueWith(_ => - { - fsProgress.TotalSize = sizeCalculator.Size; - fsProgress.ItemsCount = sizeCalculator.ItemsCount; - fsProgress.EnumerationCompleted = true; - fsProgress.Report(); - }); - - fsProgress.Report(); - progressHandler ??= new(); - - return STATask.Run(async () => - { - using var op = new ShellFileOperations2(); - var shellOperationResult = new ShellOperationResult(); - - op.Options = FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR | FILEOPERATION_FLAGS.FOF_SILENT | FILEOPERATION_FLAGS.FOF_NOERRORUI; - - if (asAdmin) - { - op.Options |= FILEOPERATION_FLAGS.FOFX_SHOWELEVATIONPROMPT | FILEOPERATION_FLAGS.FOFX_REQUIREELEVATION; - } - - op.OwnerWindow = (HWND)(nint)ownerHwnd; - - op.Options |= !overwriteOnMove ? FILEOPERATION_FLAGS.FOFX_PRESERVEFILEEXTENSIONS | FILEOPERATION_FLAGS.FOF_RENAMEONCOLLISION : FILEOPERATION_FLAGS.FOF_NOCONFIRMATION; - - for (var i = 0; i < fileToMovePath.Length; i++) - { - if (!SafetyExtensions.IgnoreExceptions(() => - { - using ShellItem shi = new(fileToMovePath[i]); - var destinationFolderPath = Path.GetDirectoryName(moveDestination[i]) - ?? throw new ArgumentException("The move destination must include a parent folder.", nameof(moveDestination)); - using ShellFolder shd = new(destinationFolderPath); - - op.QueueMoveOperation(shi, shd, Path.GetFileName(moveDestination[i])); - })) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = fileToMovePath[i], - Destination = moveDestination[i], - // HResult -1 makes the caller retry with the StorageFile API (ADS); a missing source must map to NotFound instead - HResult = MainStreamExists(fileToMovePath[i]) ? -1 : CopyEngineResult.COPYENGINE_E_PATH_NOT_FOUND_SRC - }); - } - } - - progressHandler.OwnerWindow = op.OwnerWindow; - progressHandler.AddOperation(operationID); - - var moveTcs = new TaskCompletionSource(); - - op.PreMoveItem += (s, e) => - { - if (e.SourceItem is not { } sourceItem) - return; - - if (sourceItem.GetParsingPath() is { } sourcePath) - sizeCalculator.ForceComputeFileSize(sourcePath); - fsProgress.FileName = sourceItem.Name ?? string.Empty; - fsProgress.Report(); - }; - - op.PostMoveItem += (s, e) => - { - var sourceItem = e.SourceItem; - var sourcePath = sourceItem?.GetParsingPath(); - if (sourceItem is { IsFolder: false } && sourcePath is not null) - { - if (sizeCalculator.TryGetComputedFileSize(sourcePath, out _)) - fsProgress.AddProcessedItemsCount(1); - } - - var destinationFolderPath = e.DestFolder?.GetParsingPath(); - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = e.Result.Succeeded, - Source = sourcePath, - Destination = destinationFolderPath is not null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(destinationFolderPath, e.Name) : null, - HResult = (int)e.Result - }); - - UpdateFileTagsDb(e, "move"); - }; - - op.FinishOperations += (s, e) - => moveTcs.TrySetResult(e.Result.Succeeded); - - op.UpdateProgress += (s, e) => - { - // E_FAIL, stops operation - if (progressHandler.CheckCanceled(operationID)) - throw new Win32Exception(unchecked((int)0x80004005)); - - fsProgress.Report(e.ProgressPercentage); - progressHandler.UpdateOperation(operationID, e.ProgressPercentage); - }; - - try - { - op.PerformOperations(); - } - catch - { - moveTcs.TrySetResult(false); - } - - progressHandler.RemoveOperation(operationID); - - cts.Cancel(); - - return (await moveTcs.Task, shellOperationResult); - }, App.Logger); - } - - public static Task<(bool, ShellOperationResult)> CopyItemAsync(string[] fileToCopyPath, string[] copyDestination, bool overwriteOnCopy, long ownerHwnd, bool asAdmin, IProgress progress, string operationID = "") - { - operationID = string.IsNullOrEmpty(operationID) ? Guid.NewGuid().ToString() : operationID; - - StatusCenterItemProgressModel fsProgress = new( - progress, - false, - FileSystemStatusCode.InProgress); - - var cts = new CancellationTokenSource(); - var sizeCalculator = new FileSizeCalculator(fileToCopyPath); - - // Track the count and update the progress - sizeCalculator.ItemsCountChanged += (newCount) => - { - fsProgress.ItemsCount = newCount; - fsProgress.Report(); - }; - - var sizeTask = sizeCalculator.ComputeSizeAsync(cts.Token); - sizeTask.ContinueWith(_ => - { - fsProgress.TotalSize = sizeCalculator.Size; - fsProgress.ItemsCount = sizeCalculator.ItemsCount; - fsProgress.EnumerationCompleted = true; - fsProgress.Report(); - }); - - fsProgress.Report(); - progressHandler ??= new(); - - return STATask.Run(async () => - { - using var op = new ShellFileOperations2(); - - var shellOperationResult = new ShellOperationResult(); - - op.Options = FILEOPERATION_FLAGS.FOF_NOCONFIRMMKDIR | FILEOPERATION_FLAGS.FOF_SILENT | FILEOPERATION_FLAGS.FOF_NOERRORUI; - - if (asAdmin) - { - op.Options |= FILEOPERATION_FLAGS.FOFX_SHOWELEVATIONPROMPT | FILEOPERATION_FLAGS.FOFX_REQUIREELEVATION; - } - - op.OwnerWindow = (HWND)(nint)ownerHwnd; - - op.Options |= !overwriteOnCopy ? FILEOPERATION_FLAGS.FOFX_PRESERVEFILEEXTENSIONS | FILEOPERATION_FLAGS.FOF_RENAMEONCOLLISION : FILEOPERATION_FLAGS.FOF_NOCONFIRMATION; - - for (var i = 0; i < fileToCopyPath.Length; i++) - { - if (!SafetyExtensions.IgnoreExceptions(() => - { - using ShellItem shi = new(fileToCopyPath[i]); - var destinationFolderPath = Path.GetDirectoryName(copyDestination[i]) - ?? throw new ArgumentException("The copy destination must include a parent folder.", nameof(copyDestination)); - using ShellFolder shd = new(destinationFolderPath); - - var fileName = GetIncrementalName(overwriteOnCopy, copyDestination[i], fileToCopyPath[i]); - // Perform a copy operation - op.QueueCopyOperation(shi, shd, fileName); - })) - { - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = false, - Source = fileToCopyPath[i], - Destination = copyDestination[i], - // HResult -1 makes the caller retry with the StorageFile API (ADS); a missing source must map to NotFound instead - HResult = MainStreamExists(fileToCopyPath[i]) ? -1 : CopyEngineResult.COPYENGINE_E_PATH_NOT_FOUND_SRC - }); - } - } - - progressHandler.OwnerWindow = op.OwnerWindow; - progressHandler.AddOperation(operationID); - - var copyTcs = new TaskCompletionSource(); - - op.PreCopyItem += (s, e) => - { - if (e.SourceItem is not { } sourceItem) - return; - - if (sourceItem.GetParsingPath() is { } sourcePath) - sizeCalculator.ForceComputeFileSize(sourcePath); - fsProgress.FileName = sourceItem.Name ?? string.Empty; - fsProgress.Report(); - }; - - op.PostCopyItem += (s, e) => - { - var sourceItem = e.SourceItem; - var sourcePath = sourceItem?.GetParsingPath(); - if (sourceItem is { IsFolder: false } && sourcePath is not null) - { - if (sizeCalculator.TryGetComputedFileSize(sourcePath, out _)) - fsProgress.AddProcessedItemsCount(1); - } - - var destinationFolderPath = e.DestFolder?.GetParsingPath(); - shellOperationResult.Items.Add(new ShellOperationItemResult() - { - Succeeded = e.Result.Succeeded, - Source = sourcePath, - Destination = destinationFolderPath is not null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(destinationFolderPath, e.Name) : null, - HResult = (int)e.Result - }); - - UpdateFileTagsDb(e, "copy"); - }; - - op.FinishOperations += (s, e) - => copyTcs.TrySetResult(e.Result.Succeeded); - - op.UpdateProgress += (s, e) => - { - // E_FAIL, stops operation - if (progressHandler.CheckCanceled(operationID)) - throw new Win32Exception(unchecked((int)0x80004005)); - - fsProgress.Report(e.ProgressPercentage); - progressHandler.UpdateOperation(operationID, e.ProgressPercentage); - }; - - try - { - op.PerformOperations(); - } - catch - { - copyTcs.TrySetResult(false); - } - - progressHandler.RemoveOperation(operationID); - - cts.Cancel(); - - return (await copyTcs.Task, shellOperationResult); - }, App.Logger); - } - - public static void TryCancelOperation(string operationId) - => progressHandler?.TryCancel(operationId); - - public static IEnumerable? CheckFileInUse(string[] fileToCheckPath) - { - var processes = SafetyExtensions.IgnoreExceptions(() => Win32Helper.WhoIsLocking(fileToCheckPath), App.Logger); - - if (processes is not null) - { - var win32proc = processes.Select(x => new Win32Process() - { - Name = x.ProcessName, - Pid = x.Id, - FileName = SafetyExtensions.IgnoreExceptions(() => x.MainModule?.FileName), - AppName = SafetyExtensions.IgnoreExceptions(() => x.MainModule?.FileVersionInfo?.FileDescription) - }).ToList(); - processes.ForEach(x => x.Dispose()); - - return win32proc; - } - else - { - return null; - } - } - - /// - /// Whether to run the shell's link resolution (which may search for moved targets and touch the - /// network). Pass when only the data stored in the link file is needed, - /// e.g. for listing items. - /// - public static async Task ParseLinkAsync(string linkPath, bool resolveTarget = true) - { - if (string.IsNullOrEmpty(linkPath)) - return null; - - string targetPath = string.Empty; - - try - { - if (FileExtensionHelpers.IsShortcutFile(linkPath)) - { - using var link = resolveTarget - ? new ShellLink(linkPath, SLR_FLAGS.SLR_NO_UI_WITH_MSG_PUMP, timeout: TimeSpan.FromMilliseconds(100)) - : new ShellLink(linkPath, resolve: false); - targetPath = link.TargetPath; - - // Broken shortcut (rooted target that's gone) keeps the delete prompt; app/shell targets aren't rooted - if (resolveTarget && Path.IsPathRooted(targetPath) && - !targetPath.StartsWith(@"\\", StringComparison.Ordinal) && !Path.Exists(targetPath)) - { - return new ShellLinkItem { TargetPath = targetPath, InvalidTarget = true }; - } - - return ShellFolderExtensions.GetShellLinkItem(link); - } - else if (FileExtensionHelpers.IsWebLinkFile(linkPath)) - { - targetPath = await STATask.Run(() => InternetShortcut.Load(linkPath), App.Logger); - return string.IsNullOrEmpty(targetPath) ? - new ShellLinkItem - { - TargetPath = string.Empty, - InvalidTarget = true - } : new ShellLinkItem { TargetPath = targetPath }; - } - return null; - } - catch (FileNotFoundException ex) // Could not parse shortcut - { - App.Logger?.LogWarning(ex, ex.Message); - // Return a item containing the invalid target path - return new ShellLinkItem - { - TargetPath = string.IsNullOrEmpty(targetPath) ? string.Empty : targetPath, - InvalidTarget = true - }; - } - catch (Exception ex) - { - // Could not parse shortcut - App.Logger.LogWarning(ex, ex.Message); - return null; - } - } - - public static Task CreateOrUpdateLinkAsync(string linkSavePath, string? targetPath, string? arguments = "", string? workingDirectory = "", bool runAsAdmin = false, SHOW_WINDOW_CMD showWindowCommand = SHOW_WINDOW_CMD.SW_NORMAL) - { - try - { - ArgumentNullException.ThrowIfNull(targetPath); - if (FileExtensionHelpers.IsShortcutFile(linkSavePath)) - { - using var newLink = new ShellLink(targetPath, arguments, workingDirectory); - - // Check if the target is a file - if (File.Exists(targetPath)) - newLink.RunAsAdministrator = runAsAdmin; - - newLink.SaveAs(linkSavePath); // Overwrite if exists - - // ShowState has to be set after SaveAs has been called, otherwise an UnauthorizedAccessException gets thrown in some cases - newLink.ShowState = showWindowCommand; - - return Task.FromResult(true); - } - else if (FileExtensionHelpers.IsWebLinkFile(linkSavePath)) - { - return STATask.Run(() => - { - InternetShortcut.Save(linkSavePath, targetPath); - return true; - }, App.Logger); - } - } - catch (UnauthorizedAccessException ex) - { - // Could not create shortcut - App.Logger.LogInformation(ex, "Failed to create shortcut"); - } - catch (Exception ex) - { - // Could not create shortcut - App.Logger.LogWarning(ex, ex.Message); - } - - return Task.FromResult(false); - } - - public static bool SetLinkIcon(string filePath, string? iconFile, int iconIndex) - { - iconFile ??= string.Empty; - var ext = Path.GetExtension(filePath).ToLowerInvariant(); - - try - { - return ext switch - { - ".lnk" => TrySetLnkShortcutIcon(filePath, iconFile, iconIndex), - ".url" => TrySetUrlShortcutIcon(filePath, iconFile, iconIndex), - _ => false, - }; - } - catch (UnauthorizedAccessException) - { - string psScript; - filePath = filePath.Replace("'", "''"); - iconFile = iconFile.Replace("'", "''"); - - if(ext == ".url") - { - psScript = $@" - $path = '{filePath}' - $iconFile = '{iconFile}' - $iconIndex = '{iconIndex}' - $content = Get-Content -LiteralPath $path - - $content = $content | Where-Object {{ $_ -notmatch '^IconFile=' -and $_ -notmatch '^IconIndex=' }} - - $newContent = foreach ($line in $content) {{ - $line - if ($line -eq '[InternetShortcut]') {{ - ""IconFile=$iconFile"" - ""IconIndex=$iconIndex"" - }} - }} - $newContent | Set-Content -LiteralPath $path -Encoding UTF8 - "; - } - else - { - psScript = $@" - $FilePath = '{filePath}' - $IconFile = '{iconFile}' - $IconIndex = '{iconIndex}' - - $Shell = New-Object -ComObject WScript.Shell - $Shortcut = $Shell.CreateShortcut($FilePath) - $Shortcut.IconLocation = ""$IconFile, $IconIndex"" - $Shortcut.Save() - "; - } - - var base64EncodedScript = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(psScript)); - - ProcessStartInfo startInfo = new ProcessStartInfo() - { - FileName = "powershell.exe", - Arguments = $"-NoProfile -EncodedCommand {base64EncodedScript}", - Verb = "runas", - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - UseShellExecute = true - }; - - // Start the process - Process process = new Process() { StartInfo = startInfo }; - process.Start(); - process.WaitForExit(); - - return true; - } - catch (Exception ex) - { - // Could not create shortcut - App.Logger.LogWarning(ex, ex.Message); - } - - return false; - } - - private static bool TrySetUrlShortcutIcon(string filePath, string iconFile, int iconIndex) - { - var fileExist = File.Exists(filePath); - if (!fileExist) - { - return false; - } - - var lines = File.ReadAllLines(filePath).ToList(); - var hasInternetShortcutHeader = lines.Any(l => l.Trim().Equals("[InternetShortcut]", StringComparison.OrdinalIgnoreCase)); - - if (!hasInternetShortcutHeader) - { - return false; - } - - lines.RemoveAll(l => - l.StartsWith("IconFile=", StringComparison.OrdinalIgnoreCase) || - l.StartsWith("IconIndex=", StringComparison.OrdinalIgnoreCase)); - - int index = 0; - int insertedIndex = 0; - foreach(var line in lines) - { - var isInternetShortcutHeader = line.Trim().Equals("[InternetShortcut]", StringComparison.OrdinalIgnoreCase); - if(isInternetShortcutHeader) - { - insertedIndex = index + 1; - break; - } - - index++; - } - - if (insertedIndex > 0 && !string.IsNullOrEmpty(iconFile)) - { - lines.Insert(insertedIndex, $"IconFile={iconFile}"); - lines.Insert(insertedIndex + 1, $"IconIndex={iconIndex}"); - } - - File.WriteAllLines(filePath, lines); - - return true; - } - - private static bool TrySetLnkShortcutIcon(string filePath, string iconFile, int iconIndex) - { - using var link = new ShellLink(filePath, SLR_FLAGS.SLR_NO_UI_WITH_MSG_PUMP, timeout: TimeSpan.FromMilliseconds(100)); - if (string.IsNullOrWhiteSpace(iconFile)) - { - link.IconLocation = new IconLocation(string.Empty, 0); - } - else - { - link.IconLocation = new IconLocation(iconFile, iconIndex); - } - link.SaveAs(filePath); // Overwrite if exists - - return true; - } - - public static Task OpenObjectPickerAsync(long hWnd) - => WindowsObjectPicker.OpenObjectPickerAsync((nint)hWnd, App.Logger); - - private static ShellItem? GetFirstFile(ShellItem shi) - { - if (!shi.IsFolder || shi.IsStream) - { - return shi; - } - using var shf = new ShellFolder(shi); - if (shf.FirstOrDefault(x => !x.IsFolder || x.IsStream) is ShellItem item) - { - return item; - } - foreach (var shsfi in shf.Where(x => x.IsFolder && !x.IsStream)) - { - using var shsf = new ShellFolder(shsfi); - if (GetFirstFile(shsf) is ShellItem item2) - { - return item2; - } - } - return null; - } - - private static void UpdateFileTagsDb(ShellFileOperations2.ShellFileOpEventArgs e, string operationType) - { - var dbInstance = FileTagsHelper.GetDbInstance(); - if (e.Result.Succeeded && e.SourceItem.GetParsingPath() is { } sourcePath) - { - var destPath = e.DestFolder.GetParsingPath(); - var sourceFolderPath = Path.GetDirectoryName(sourcePath); - var destination = operationType switch - { - "delete" => e.DestItem.GetParsingPath(), - "rename" => sourceFolderPath is not null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(sourceFolderPath, e.Name) : null, - "copy" => destPath is not null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(destPath, e.Name) : null, - _ => destPath is not null && !string.IsNullOrEmpty(e.Name) ? Path.Combine(destPath, e.Name) : null - }; - if (destination is null) - { - dbInstance.SetTags(sourcePath, null, []); // remove tag from deleted files - } - else - { - SafetyExtensions.IgnoreExceptions(() => - { - if (operationType == "copy") - { - var tag = dbInstance.GetTags(sourcePath, null); - - dbInstance.SetTags(destination, FileTagsHelper.GetFileFRN(destination), tag); // copy tag to new files - using var si = new ShellItem(destination); - if (si.IsFolder) // File tag is not copied automatically for folders - { - _ = FileTagsHelper.WriteFileTagAsync(destination, tag); - } - } - else - { - dbInstance.UpdateTag(sourcePath, FileTagsHelper.GetFileFRN(destination), destination); // move tag to new files - } - }, App.Logger); - } - if (e.Result == HRESULT.COPYENGINE_S_DONT_PROCESS_CHILDREN) // child items not processed, update manually - { - var tags = dbInstance.GetAllUnderPath(sourcePath).ToList(); - if (destination is null) // remove tag for items contained in the folder - { - tags.ForEach(t => dbInstance.SetTags(t.FilePath, null, [])); - } - else - { - if (operationType == "copy") // copy tag for items contained in the folder - { - tags.ForEach(t => - { - SafetyExtensions.IgnoreExceptions(() => - { - var subPath = t.FilePath.Replace(sourcePath, destination, StringComparison.Ordinal); - dbInstance.SetTags(subPath, FileTagsHelper.GetFileFRN(subPath), t.Tags ?? []); - }, App.Logger); - }); - } - else // move tag to new files - { - tags.ForEach(t => - { - SafetyExtensions.IgnoreExceptions(() => - { - var subPath = t.FilePath.Replace(sourcePath, destination, StringComparison.Ordinal); - dbInstance.UpdateTag(t.FilePath, FileTagsHelper.GetFileFRN(subPath), subPath); - }, App.Logger); - }); - } - } - } - } - } - - public static void WaitForCompletion() - => progressHandler?.WaitForCompletion(); - - private sealed partial class ProgressHandler : Disposable - { - private readonly ManualResetEvent operationsCompletedEvent; - - public sealed class OperationWithProgress - { - public double Progress { get; set; } - public bool Canceled { get; set; } - } - - private readonly ConcurrentDictionary operations; - - public HWND OwnerWindow { get; set; } - - public ProgressHandler() - { - operations = new ConcurrentDictionary(); - operationsCompletedEvent = new ManualResetEvent(true); - } - - public int Progress - { - get - { - var ongoing = operations.ToArray().Where(x => !x.Value.Canceled); - return ongoing.Any() ? (int)ongoing.Average(x => x.Value.Progress) : 0; - } - } - - public void AddOperation(string uid) - { - operations.TryAdd(uid, new OperationWithProgress()); - operationsCompletedEvent.Reset(); - } - - public void RemoveOperation(string uid) - { - operations.TryRemove(uid, out _); - if (!operations.Any()) - { - operationsCompletedEvent.Set(); - } - } - - public void UpdateOperation(string uid, double progress) - { - if (operations.TryGetValue(uid, out var op)) - { - op.Progress = progress; - } - } - - public bool CheckCanceled(string uid) - { - return !operations.TryGetValue(uid, out var op) || op.Canceled; - } - - public void TryCancel(string uid) - { - if (operations.TryGetValue(uid, out var op)) - { - op.Canceled = true; - } - } - - public void WaitForCompletion() - { - operationsCompletedEvent.WaitOne(); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - operationsCompletedEvent?.Dispose(); - } - } - } - - private static string GetIncrementalName(bool overWriteOnCopy, string filePathToCheck, string filePathToCopy) - { - if ((!Path.Exists(filePathToCheck)) || overWriteOnCopy || filePathToCheck == filePathToCopy) - return Path.GetFileName(filePathToCheck); - - var index = 2; - var filePath = filePathToCheck; - if (Path.HasExtension(filePathToCheck)) - filePath = filePathToCheck.Substring(0, filePathToCheck.LastIndexOf('.')); - - Func genFilePath = x => string.Concat([filePath, " (", x.ToString(), ")", Path.GetExtension(filePathToCheck)]); - - while (Path.Exists(genFilePath(index))) - index++; - - return Path.GetFileName(genFilePath(index)); - } - - private static bool MainStreamExists(string path) - { - // Path.Exists is always false for ADS paths (file.txt:stream), so check the main stream's path - var fileName = Path.GetFileName(path); - var colonIndex = fileName.IndexOf(':'); - if (colonIndex is not -1) - path = path[..(path.Length - fileName.Length + colonIndex)]; - - return Path.Exists(path); - } - } -} diff --git a/src/Files.App/Utils/Storage/Operations/FileSizeCalculator.Windows.cs b/src/Files.App/Utils/Storage/Operations/FileSizeCalculator.Windows.cs deleted file mode 100644 index b48ef7e5200c..000000000000 --- a/src/Files.App/Utils/Storage/Operations/FileSizeCalculator.Windows.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; - -namespace Files.App.Utils.Storage.Operations -{ - internal sealed partial class FileSizeCalculator - { - public async Task ComputeSizeAsync(CancellationToken cancellationToken = default) - { - await Parallel.ForEachAsync( - _paths, - cancellationToken, - (path, token) => - { - ComputeSizeRecursively(path, token); - return ValueTask.CompletedTask; - }); - - Completed = true; - - unsafe void ComputeSizeRecursively(string path, CancellationToken token) - { - var queue = new Queue(); - if (!Win32Helper.HasFileAttribute(path, FileAttributes.Directory)) - { - ComputeFileSize(path); - } - else - { - queue.Enqueue(path); - - while (queue.TryDequeue(out var directory)) - { - WIN32_FIND_DATAW findData = default; - - fixed (char* pszFilePath = directory + "\\*.*") - { - var hFile = PInvoke.FindFirstFileEx( - pszFilePath, - FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - null, - FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - - if (!hFile.IsNull) - { - try - { - do - { - FILE_FLAGS_AND_ATTRIBUTES attributes = (FILE_FLAGS_AND_ATTRIBUTES)findData.dwFileAttributes; - - if (attributes.HasFlag(FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_REPARSE_POINT)) - // Skip symbolic links and junctions - continue; - - var itemPath = Path.Combine(directory, findData.cFileName.ToString()); - - // Skip current and parent directory entries - var fileName = findData.cFileName.ToString(); - if (fileName.Equals(".", StringComparison.OrdinalIgnoreCase) || - fileName.Equals("..", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - if (attributes.HasFlag(FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_DIRECTORY)) - { - queue.Enqueue(itemPath); - } - else - { - ComputeFileSize(itemPath); - } - - if (token.IsCancellationRequested) - break; - } - while (PInvoke.FindNextFile(hFile, &findData)); - } - finally - { - PInvoke.FindClose(hFile); - } - } - } - } - } - } - } - - private long ComputeFileSize(string path) - { - if (_computedFiles.TryGetValue(path, out var size)) - return size; - - using var hFile = PInvoke.CreateFile( - path, - (uint)FILE_ACCESS_RIGHTS.FILE_READ_ATTRIBUTES, - FILE_SHARE_MODE.FILE_SHARE_READ, - null, - FILE_CREATION_DISPOSITION.OPEN_EXISTING, - 0, - null); - - if (!hFile.IsInvalid && PInvoke.GetFileSizeEx(hFile, out size) && _computedFiles.TryAdd(path, size)) - { - Interlocked.Add(ref _size, size); - ItemsCountChanged?.Invoke(ItemsCount); - } - - return size; - } - - public void ForceComputeFileSize(string path) - { - if (!Win32Helper.HasFileAttribute(path, FileAttributes.Directory)) - ComputeFileSize(path); - } - } -} diff --git a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Linux.cs b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Linux.cs index df19516d0ab3..040d75f01a27 100644 --- a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Linux.cs +++ b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Linux.Clipboard; using Microsoft.Extensions.Logging; using System.IO; @@ -46,4 +45,3 @@ public static async Task> GetDraggedStorageIte } } } -#endif diff --git a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Windows.cs b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Windows.cs deleted file mode 100644 index 590e6293d515..000000000000 --- a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.Windows.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using System.IO; -using System.Runtime.InteropServices; -using Windows.ApplicationModel.DataTransfer; -using Windows.Storage.Streams; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; -using Windows.Win32.UI.Shell; -using FileAttributes = System.IO.FileAttributes; - -namespace Files.App.Utils.Storage -{ - public sealed partial class FilesystemHelpers - { - public static bool HasDraggedStorageItems(DataPackageView packageView) - { - return packageView is not null && (packageView.Contains(StandardDataFormats.StorageItems) || packageView.Contains("FileDrop")); - } - - public static async Task> GetDraggedStorageItems(DataPackageView packageView) - { - var itemsList = new List(); - var hasVirtualItems = false; - - if (packageView.Contains(StandardDataFormats.StorageItems)) - { - try - { - var source = await packageView.GetStorageItemsAsync(); - itemsList.AddRange(source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A dragged storage item could not be converted."))); - } - catch (Exception ex) when ((uint)ex.HResult == 0x80040064 || (uint)ex.HResult == 0x8004006A) - { - hasVirtualItems = true; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - return itemsList; - } - } - - // workaround for pasting folders from remote desktop (#12318) - try - { - if (hasVirtualItems && packageView.Contains("FileContents")) - { - var dataObject = ShellDataObject.GetClipboard(); - if (dataObject is null) - return itemsList; - - var descriptors = ShellDataObject.GetFileDescriptors(dataObject); - for (var ii = 0; ii < descriptors.Count; ii++) - { - var descriptor = descriptors[ii]; - if (descriptor.Attributes.HasFlag(FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_DIRECTORY)) - itemsList.Add(new VirtualStorageFolder(descriptor.Name).FromStorageItem()!); - else if (ShellDataObject.TryGetFileContents(dataObject, ii, out var stream, out var medium)) - { - var streamContent = new ComStreamWrapper(stream!, medium); - itemsList.Add(new VirtualStorageFile(streamContent, descriptor.Name).FromStorageItem()!); - } - } - } - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - - // workaround for GetStorageItemsAsync() bug that only yields 16 items at most - // https://learn.microsoft.com/windows/win32/shell/clipboard#cf_hdrop - if (packageView.Contains("FileDrop")) - { - var fileDropData = await SafetyExtensions.IgnoreExceptions( - () => packageView.GetDataAsync("FileDrop").AsTask()); - if (fileDropData is IRandomAccessStream stream) - { - stream.Seek(0); - - byte[]? dropBytes = null; - int bytesRead = 0; - try - { - dropBytes = new byte[stream.Size]; - bytesRead = await stream.AsStreamForRead().ReadAsync(dropBytes); - } - catch (COMException) - { - } - - if (bytesRead > 0) - { - IntPtr dropStructPointer = Marshal.AllocHGlobal(dropBytes!.Length); - - try - { - Marshal.Copy(dropBytes, 0, dropStructPointer, dropBytes.Length); - HDROP dropStructHandle = new(dropStructPointer); - - var itemPaths = new List(); - uint filesCount = PInvoke.DragQueryFile(dropStructHandle, uint.MaxValue, Span.Empty); - for (uint i = 0; i < filesCount; i++) - { - uint charsNeeded = PInvoke.DragQueryFile(dropStructHandle, i, Span.Empty); - uint bufferSpaceRequired = charsNeeded + 1; // include space for terminating null character - char[] buffer = new char[bufferSpaceRequired]; - uint charsCopied = PInvoke.DragQueryFile(dropStructHandle, i, buffer); - - if (charsCopied > 0) - { - string path = new(buffer, 0, (int)charsCopied); - itemPaths.Add(Path.GetFullPath(path)); - } - } - - foreach (var path in itemPaths) - { - var isDirectory = Win32Helper.HasFileAttribute(path, FileAttributes.Directory); - itemsList.Add(StorageHelpers.FromPathAndType(path, isDirectory ? FilesystemItemType.Directory : FilesystemItemType.File)); - } - } - finally - { - Marshal.FreeHGlobal(dropStructPointer); - } - } - } - } - - itemsList = itemsList.DistinctBy(x => string.IsNullOrEmpty(x.Path) ? x.Name : x.Path).ToList(); - return itemsList; - } - - } -} diff --git a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs index feb5a8ae1a0d..c1094395a409 100644 --- a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs +++ b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs @@ -182,37 +182,15 @@ showDialog is DeleteConfirmationPolicies.PermanentOnly && public Task DeleteItemAsync(IStorageItemWithPath source, DeleteConfirmationPolicies showDialog, bool permanently, bool registerHistory) => DeleteItemsAsync(source.CreateEnumerable(), showDialog, permanently, registerHistory); -#if WINDOWS - public Task DeleteItemsAsync(IEnumerable source, DeleteConfirmationPolicies showDialog, bool permanently, bool registerHistory) - => DeleteItemsAsync(source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for deletion.")), showDialog, permanently, registerHistory); -#endif - -#if WINDOWS - public Task DeleteItemAsync(IStorageItem source, DeleteConfirmationPolicies showDialog, bool permanently, bool registerHistory) - => DeleteItemAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for deletion."), showDialog, permanently, registerHistory); -#endif - -#if WINDOWS - public Task RestoreItemFromTrashAsync(IStorageItem source, string destination, bool registerHistory) - => RestoreItemFromTrashAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for restoration."), destination, registerHistory); -#endif - -#if WINDOWS - public Task RestoreItemsFromTrashAsync(IEnumerable source, IEnumerable destination, bool registerHistory) - => RestoreItemsFromTrashAsync(source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for restoration.")), destination, registerHistory); -#endif + + + public Task RestoreItemFromTrashAsync(IStorageItemWithPath source, string destination, bool registerHistory) => RestoreItemsFromTrashAsync(source.CreateEnumerable(), destination.CreateEnumerable(), registerHistory); public async Task RestoreItemsFromTrashAsync(IEnumerable source, IEnumerable destination, bool registerHistory -#if !WINDOWS , Action? historyCallback = null -#endif ) { source = await source.ToListAsync(); @@ -236,9 +214,7 @@ public async Task RestoreItemsFromTrashAsync(IEnumerable PerformOperationTypeAsync( : await CopyItemsAsync(items, destinations, showDialog, registerHistory); } -#if WINDOWS - public Task CopyItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory) - => CopyItemsAsync(source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for copying.")), destination, showDialog, registerHistory); -#endif -#if WINDOWS - public Task CopyItemAsync(IStorageItem source, string destination, bool showDialog, bool registerHistory) - => CopyItemAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for copying."), destination, showDialog, registerHistory); -#endif public async Task CopyItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory -#if !WINDOWS , Action? historyCallback = null -#endif ) { source = await source.ToListAsync(); @@ -420,9 +384,7 @@ public async Task CopyItemsAsync(IEnumerable destination, itemsCount); -#if !WINDOWS historyCallback?.Invoke(history); -#endif return returnStatus; } @@ -496,22 +458,10 @@ public async Task CopyItemsFromClipboard(DataPackageView packageVi return ReturnResult.BadArgumentException; } -#if WINDOWS - public Task MoveItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory) - => MoveItemsAsync(source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for moving.")), destination, showDialog, registerHistory); -#endif -#if WINDOWS - public Task MoveItemAsync(IStorageItem source, string destination, bool showDialog, bool registerHistory) - => MoveItemAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for moving."), destination, showDialog, registerHistory); -#endif public async Task MoveItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory -#if !WINDOWS , Action? historyCallback = null -#endif ) { source = await source.ToListAsync(); @@ -584,9 +534,7 @@ public async Task MoveItemsAsync(IEnumerable destination, itemsCount); -#if !WINDOWS historyCallback?.Invoke(history); -#endif return returnStatus; } @@ -630,11 +578,6 @@ public async Task MoveItemsFromClipboard(DataPackageView packageVi return returnStatus; } -#if WINDOWS - public Task RenameAsync(IStorageItem source, string newName, NameCollisionOption collision, bool registerHistory, bool showExtensionDialog = true) - => RenameAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for renaming."), newName, collision, registerHistory, showExtensionDialog); -#endif public async Task RenameAsync(IStorageItemWithPath source, string newName, NameCollisionOption collision, bool registerHistory, bool showExtensionDialog = true) { diff --git a/src/Files.App/Utils/Storage/Operations/FilesystemOperations.Windows.cs b/src/Files.App/Utils/Storage/Operations/FilesystemOperations.Windows.cs deleted file mode 100644 index 84349aa0f8fa..000000000000 --- a/src/Files.App/Utils/Storage/Operations/FilesystemOperations.Windows.cs +++ /dev/null @@ -1,1077 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using Microsoft.UI.Xaml.Controls; -using System.IO; -using System.Text; -using Windows.Foundation.Metadata; -using Windows.Storage; -using Windows.Win32; - -namespace Files.App.Utils.Storage -{ - /// - /// Provides group of file system operation for given page instance. - /// - public sealed partial class FilesystemOperations : IFilesystemOperations - { - private readonly IStorageTrashBinService StorageTrashBinService = Ioc.Default.GetRequiredService(); - - private IShellPage? _associatedInstance; - private IShellPage AssociatedInstance - => _associatedInstance ?? throw new ObjectDisposedException(nameof(FilesystemOperations)); - private ShellViewModel ShellViewModel - => AssociatedInstance.GetRequiredShellViewModel(); - - public FilesystemOperations(IShellPage associatedInstance) - { - _associatedInstance = associatedInstance; - } - - public async Task<(IStorageHistory?, IStorageItem?)> CreateAsync(IStorageItemWithPath source, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) - { - IStorageItemWithPath? item = null; - FilesystemResult fsResult = (FilesystemResult)false; - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, 1); - fsProgress.Report(); - - try - { - switch (source.ItemType) - { - case FilesystemItemType.File: - { - var newEntryInfo = await ShellNewEntryExtensions.GetNewContextMenuEntryForType(Path.GetExtension(source.Path)); - if (newEntryInfo is null) - { - var fsFolderResult = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(source.Path)); - fsResult = fsFolderResult; - if (fsResult) - { - var folder = fsFolderResult.Result - ?? throw new InvalidOperationException("The destination folder could not be opened for file creation."); - var fileName = Path.GetFileName(source.Path)!; - var fsCreateResult = await FilesystemTasks.Wrap(() => folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask()); - fsResult = fsCreateResult; - var createdFile = fsCreateResult.Result; - if (fsCreateResult && createdFile is null) - throw new InvalidOperationException("The file creation completed without returning the created file."); - item = createdFile?.FromStorageItem(); - } - if (fsResult == FileSystemStatusCode.Unauthorized) - { - // Can't do anything, already tried with admin FTP - } - } - else - { - var fsCreateResult = await newEntryInfo.Create(source.Path, AssociatedInstance); - fsResult = fsCreateResult; - if (fsResult && fsCreateResult.Result is null) - throw new InvalidOperationException("The file creation completed without returning the created file."); - item = fsCreateResult.Result?.FromStorageItem(); - if (fsResult == FileSystemStatusCode.Unauthorized) - { - // Can't do anything, already tried with admin FTP - } - } - - break; - } - - case FilesystemItemType.Directory: - { - var fsFolderResult = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(source.Path)); - fsResult = fsFolderResult; - if (fsResult) - { - var folder = fsFolderResult.Result - ?? throw new InvalidOperationException("The destination folder could not be opened for folder creation."); - var folderName = Path.GetFileName(source.Path)!; - var fsCreateResult = await FilesystemTasks.Wrap(() => folder.CreateFolderAsync(folderName, CreationCollisionOption.GenerateUniqueName).AsTask()); - fsResult = fsCreateResult; - var createdFolder = fsCreateResult.Result; - if (fsCreateResult && createdFolder is null) - throw new InvalidOperationException("The folder creation completed without returning the created folder."); - item = createdFolder?.FromStorageItem(); - } - if (fsResult == FileSystemStatusCode.Unauthorized) - { - // Can't do anything, already tried with admin FTP - } - break; - } - - default: - Debugger.Break(); - break; - } - - fsProgress.AddProcessedItemsCount(1); - fsProgress.ReportStatus(fsResult); - return item is not null - ? (new StorageHistory(FileOperationType.CreateNew, item.CreateList(), null), item.Item) - : (null, null); - } - catch (Exception e) - { - fsProgress.ReportStatus(FilesystemTasks.GetErrorCode(e)); - return (null, null); - } - } - - public Task CopyAsync(IStorageItem source, string destination, NameCollisionOption collision, IProgress? progress, CancellationToken cancellationToken) - { - return CopyAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for copying."), destination, collision, progress, cancellationToken); - } - - public async Task CopyAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress? progress, CancellationToken cancellationToken) - { - StatusCenterItemProgressModel fsProgress = new( - progress, - true, - FileSystemStatusCode.InProgress); - - fsProgress.Report(); - - if (destination.StartsWith(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.Ordinal)) - { - fsProgress.ReportStatus(FileSystemStatusCode.Unauthorized); - - // Do not paste files and folders inside the recycle bin - await DialogDisplayHelper.ShowDialogAsync( - Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), - Strings.ErrorDialogUnsupportedOperation.GetLocalizedResource()); - - return null; - } - - IStorageItem? copiedItem = null; - - if (source.ItemType == FilesystemItemType.Directory) - { - if (!string.IsNullOrWhiteSpace(source.Path) && - PathNormalization.GetParentDir(destination).IsSubPathOf(source.Path)) // We check if user tried to copy anything above the source.ItemPath - { - var destinationName = destination.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); - var sourceName = source.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); - - ContentDialog dialog = new() - { - Title = Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), - Content = $"{Strings.ErrorDialogTheDestinationFolder.GetLocalizedResource()} ({destinationName}) {Strings.ErrorDialogIsASubfolder.GetLocalizedResource()} ({sourceName})", - //PrimaryButtonText = "Skip".GetLocalizedResource(), - CloseButtonText = Strings.Cancel.GetLocalizedResource() - }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - dialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - ContentDialogResult result = await dialog.TryShowAsync(); - - if (result == ContentDialogResult.Primary) - fsProgress.ReportStatus(FileSystemStatusCode.InProgress | FileSystemStatusCode.Success); - else - fsProgress.ReportStatus(FileSystemStatusCode.InProgress | FileSystemStatusCode.Generic); - - return null; - } - else - { - // CopyFileFromApp only works on file not directories - var fsSourceFolder = await source.ToStorageItemResult(); - var fsDestinationFolder = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination), cancellationToken); - var fsResult = (FilesystemResult)(fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode); - - if (fsResult && - fsSourceFolder.Result is BaseStorageFolder sourceFolder && - fsDestinationFolder.Result is BaseStorageFolder destinationFolder) - { - if (sourceFolder is IPasswordProtectedItem ppis) - ppis.PasswordRequestedCallback = UIFilesystemHelpers.RequestPassword; - - var fsCopyResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync(sourceFolder, destinationFolder, sourceFolder.Name, collision.Convert())); - - if (sourceFolder is IPasswordProtectedItem ppiu) - ppiu.PasswordRequestedCallback = null; - - if (fsCopyResult == FileSystemStatusCode.AlreadyExists) - { - fsProgress.ReportStatus(FileSystemStatusCode.AlreadyExists); - - return null; - } - - if (fsCopyResult && fsCopyResult.Result is null) - fsCopyResult = new FilesystemResult(null, FileSystemStatusCode.Generic); - - if (fsCopyResult.Result is { } copiedFolder) - { - if (Win32Helper.HasFileAttribute(source.Path, SystemIO.FileAttributes.Hidden)) - { - // The source folder was hidden, apply hidden attribute to destination - Win32Helper.SetFileAttribute(copiedFolder.Path, SystemIO.FileAttributes.Hidden); - } - - copiedItem = copiedFolder; - } - - fsResult = fsCopyResult; - } - else if (fsResult) - { - fsResult = FileSystemStatusCode.Generic; - } - - if (fsResult == FileSystemStatusCode.Unauthorized) - { - // Cannot do anything, already tried with admin FTP - } - - fsProgress.ReportStatus(fsResult.ErrorCode); - - if (!fsResult) - return null; - } - } - else if (source.ItemType == FilesystemItemType.File) - { - var fsResult = (FilesystemResult)(bool)await Task.Run(() => PInvoke.CopyFileFromApp(source.Path, destination, true)); - - if (!fsResult) - { - Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); - - FilesystemResult destinationResult = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination), cancellationToken); - var sourceResult = await source.ToStorageItemResult(); - fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode; - - if (fsResult && - sourceResult.Result is BaseStorageFile file && - destinationResult.Result is { } destinationFolder) - { - if (file is IPasswordProtectedItem ppis) - ppis.PasswordRequestedCallback = UIFilesystemHelpers.RequestPassword; - - var fsResultCopy = new FilesystemResult(null, FileSystemStatusCode.Generic); - if (string.IsNullOrEmpty(file.Path) && collision == NameCollisionOption.GenerateUniqueName) - { - // If collision is GenerateUniqueName we will manually check for existing file and generate a new name - // HACK: If file is dragged from zip file in windows explorer for example. The file path is empty and - // GenerateUniqueName isn't working correctly. Below is a possible solution. - var desiredNewName = Path.GetFileName(file.Name); - string nameWithoutExt = Path.GetFileNameWithoutExtension(desiredNewName); - string extension = Path.GetExtension(desiredNewName); - ushort attempt = 1; - - do - { - fsResultCopy = await FilesystemTasks.WrapNullable(() => file.CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists).AsTask()); - desiredNewName = $"{nameWithoutExt} ({attempt}){extension}"; - } while (fsResultCopy.ErrorCode == FileSystemStatusCode.AlreadyExists && ++attempt < 1024); - } - else - { - fsResultCopy = await FilesystemTasks.WrapNullable(() => file.CopyAsync(destinationFolder, Path.GetFileName(file.Name)!, collision).AsTask()); - } - - if (file is IPasswordProtectedItem ppiu) - ppiu.PasswordRequestedCallback = null; - - if (fsResultCopy == FileSystemStatusCode.AlreadyExists) - { - fsProgress.ReportStatus(FileSystemStatusCode.AlreadyExists); - - return null; - } - - if (fsResultCopy && fsResultCopy.Result is null) - fsResultCopy = new FilesystemResult(null, FileSystemStatusCode.Generic); - - if (fsResultCopy.Result is { } copiedFile) - copiedItem = copiedFile; - - fsResult = fsResultCopy; - } - else if (fsResult) - { - fsResult = FileSystemStatusCode.Generic; - } - - if (fsResult == FileSystemStatusCode.Unauthorized) - { - // Cannot do anything, already tried with admin FTP - } - } - - fsProgress.ReportStatus(fsResult.ErrorCode); - - if (!fsResult) - return null; - } - - if (collision == NameCollisionOption.ReplaceExisting) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - // Cannot undo overwrite operation - return null; - } - - var pathWithType = copiedItem.FromStorageItem(destination, source.ItemType); - - return new StorageHistory(FileOperationType.Copy, source, pathWithType); - } - - public Task MoveAsync(IStorageItem source, string destination, NameCollisionOption collision, IProgress? progress, CancellationToken cancellationToken) - { - return MoveAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for moving."), destination, collision, progress, cancellationToken); - } - - public async Task MoveAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress? progress, CancellationToken cancellationToken) - { - StatusCenterItemProgressModel fsProgress = new( - progress, - true, - FileSystemStatusCode.InProgress); - - fsProgress.Report(); - - if (source.Path == destination) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - return null; - } - - if (string.IsNullOrWhiteSpace(source.Path)) - { - // Cannot move (only copy) files from MTP devices because: - // StorageItems returned in DataPackageView are read-only - // The item.Path property will be empty and there's no way of retrieving a new StorageItem with R/W access - return await CopyAsync(source, destination, collision, progress, cancellationToken); - } - - if (destination.StartsWith(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.Ordinal)) - { - fsProgress.ReportStatus(FileSystemStatusCode.Unauthorized); - - // Do not paste files and folders inside the recycle bin - await DialogDisplayHelper.ShowDialogAsync( - Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), - Strings.ErrorDialogUnsupportedOperation.GetLocalizedResource()); - - return null; - } - - IStorageItem? movedItem = null; - - if (source.ItemType == FilesystemItemType.Directory) - { - // Also check if user tried to move anything above the source.ItemPath - if (!string.IsNullOrWhiteSpace(source.Path) && - PathNormalization.GetParentDir(destination).IsSubPathOf(source.Path)) - { - var destinationName = destination.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); - var sourceName = source.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); - - ContentDialog dialog = new() - { - Title = Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), - Content = $"{Strings.ErrorDialogTheDestinationFolder.GetLocalizedResource()} ({destinationName}) {Strings.ErrorDialogIsASubfolder.GetLocalizedResource()} ({sourceName})", - //PrimaryButtonText = "Skip".GetLocalizedResource(), - CloseButtonText = Strings.Cancel.GetLocalizedResource() - }; - - if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - dialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - ContentDialogResult result = await dialog.TryShowAsync(); - - if (result == ContentDialogResult.Primary) - fsProgress.ReportStatus(FileSystemStatusCode.InProgress | FileSystemStatusCode.Success); - else - fsProgress.ReportStatus(FileSystemStatusCode.InProgress | FileSystemStatusCode.Generic); - - return null; - } - else - { - var fsResult = (FilesystemResult)(bool)await Task.Run(() => PInvoke.MoveFileFromApp(source.Path, destination)); - - if (!fsResult) - { - Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); - - var fsSourceFolder = await source.ToStorageItemResult(); - var fsDestinationFolder = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination), cancellationToken); - fsResult = fsSourceFolder.ErrorCode | fsDestinationFolder.ErrorCode; - - if (fsResult && - fsSourceFolder.Result is BaseStorageFolder sourceFolder && - fsDestinationFolder.Result is BaseStorageFolder destinationFolder) - { - if (sourceFolder is IPasswordProtectedItem ppis) - ppis.PasswordRequestedCallback = UIFilesystemHelpers.RequestPassword; - - var fsResultMove = await FilesystemTasks.WrapNullable(() => sourceFolder.MoveAsync(destinationFolder, collision).AsTask()); - - if (!fsResultMove) // Use generic move folder operation (move folder items one by one) - { - // Moving folders using Storage API can result in data loss, copy instead - //var fsResultMove = await FilesystemTasks.Wrap(() => MoveDirectoryAsync((BaseStorageFolder)fsSourceFolder, (BaseStorageFolder)fsDestinationFolder, fsSourceFolder.Result.Name, collision.Convert(), true)); - - if (await DialogDisplayHelper.ShowDialogAsync(Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), Strings.ErrorDialogUnsupportedMoveOperation.GetLocalizedResource(), "OK", Strings.Cancel.GetLocalizedResource())) - fsResultMove = await FilesystemTasks.Wrap(() => CloneDirectoryAsync(sourceFolder, destinationFolder, sourceFolder.Name, collision.Convert())); - } - - if (sourceFolder is IPasswordProtectedItem ppiu) - ppiu.PasswordRequestedCallback = null; - - if (fsResultMove == FileSystemStatusCode.AlreadyExists) - { - fsProgress.ReportStatus(FileSystemStatusCode.AlreadyExists); - - return null; - } - - if (fsResultMove && fsResultMove.Result is null) - fsResultMove = new FilesystemResult(null, FileSystemStatusCode.Generic); - - if (fsResultMove.Result is { } movedFolder) - { - if (Win32Helper.HasFileAttribute(source.Path, SystemIO.FileAttributes.Hidden)) - { - // The source folder was hidden, apply hidden attribute to destination - Win32Helper.SetFileAttribute(movedFolder.Path, SystemIO.FileAttributes.Hidden); - } - - movedItem = movedFolder; - } - fsResult = fsResultMove; - } - else if (fsResult) - { - fsResult = FileSystemStatusCode.Generic; - } - if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly) - { - // Cannot do anything, already tried with admin FTP - } - } - - fsProgress.ReportStatus(fsResult.ErrorCode); - } - } - else if (source.ItemType == FilesystemItemType.File) - { - var fsResult = (FilesystemResult)(bool)await Task.Run(() => PInvoke.MoveFileFromApp(source.Path, destination)); - - if (!fsResult) - { - Debug.WriteLine(System.Runtime.InteropServices.Marshal.GetLastWin32Error()); - - FilesystemResult destinationResult = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination), cancellationToken); - var sourceResult = await source.ToStorageItemResult(); - fsResult = sourceResult.ErrorCode | destinationResult.ErrorCode; - - if (fsResult && - sourceResult.Result is BaseStorageFile file && - destinationResult.Result is { } destinationFolder) - { - if (file is IPasswordProtectedItem ppis) - ppis.PasswordRequestedCallback = UIFilesystemHelpers.RequestPassword; - - var fsResultMove = await FilesystemTasks.Wrap(() => file.MoveAsync(destinationFolder, Path.GetFileName(file.Name)!, collision).AsTask()); - - if (file is IPasswordProtectedItem ppiu) - ppiu.PasswordRequestedCallback = null; - - if (fsResultMove == FileSystemStatusCode.AlreadyExists) - { - fsProgress.ReportStatus(FileSystemStatusCode.AlreadyExists); - - return null; - } - - if (fsResultMove) - movedItem = file; - - fsResult = fsResultMove; - } - else if (fsResult) - { - fsResult = FileSystemStatusCode.Generic; - } - if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly) - { - // Cannot do anything, already tried with admin FTP - } - } - fsProgress.ReportStatus(fsResult.ErrorCode); - } - - if (collision == NameCollisionOption.ReplaceExisting) - { - // Cannot undo overwrite operation - return null; - } - - bool sourceInCurrentFolder = PathNormalization.TrimPath(ShellViewModel.CurrentFolder?.ItemPath) == PathNormalization.GetParentDir(source.Path); - if (fsProgress.Status == FileSystemStatusCode.Success && sourceInCurrentFolder) - { - await ShellViewModel.RemoveFileOrFolderAsync(source.Path); - await ShellViewModel.ApplyFilesAndFoldersChangesAsync(); - } - - var pathWithType = movedItem.FromStorageItem(destination, source.ItemType); - - return new StorageHistory(FileOperationType.Move, source, pathWithType); - } - - public Task DeleteAsync(IStorageItem source, IProgress? progress, bool permanently, CancellationToken cancellationToken) - { - return DeleteAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for deletion."), progress, permanently, cancellationToken); - } - - public async Task DeleteAsync(IStorageItemWithPath source, IProgress? progress, bool permanently, CancellationToken cancellationToken) - { - StatusCenterItemProgressModel fsProgress = new( - progress, - true, - FileSystemStatusCode.InProgress); - - fsProgress.Report(); - - bool deleteFromRecycleBin = StorageTrashBinService.IsUnderTrashBin(source.Path); - - FilesystemResult fsResult = FileSystemStatusCode.InProgress; - - if (permanently) - { - fsResult = (FilesystemResult)(bool)PInvoke.DeleteFileFromApp(source.Path); - } - if (!fsResult) - { - if (source.ItemType == FilesystemItemType.File) - { - fsResult = await ShellViewModel.GetFileFromPathAsync(source.Path, cancellationToken) - .OnSuccess((t) => (t ?? throw new InvalidOperationException($"The file '{source.Path}' could not be opened.")) - .DeleteAsync(permanently ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).AsTask()); - } - else if (source.ItemType == FilesystemItemType.Directory) - { - fsResult = await ShellViewModel.GetFolderFromPathAsync(source.Path, cancellationToken) - .OnSuccess((t) => (t ?? throw new InvalidOperationException($"The folder '{source.Path}' could not be opened.")) - .DeleteAsync(permanently ? StorageDeleteOption.PermanentDelete : StorageDeleteOption.Default).AsTask()); - } - } - - fsProgress.ReportStatus(fsResult); - - if (fsResult == FileSystemStatusCode.Unauthorized) - { - // Cannot do anything, already tried with admin FTP - } - else if (fsResult == FileSystemStatusCode.InUse) - { - // TODO: Retry - await DialogDisplayHelper.ShowDialogAsync(DynamicDialogFactory.GetFor_FileInUseDialog()); - } - - if (deleteFromRecycleBin) - { - // Recycle bin also stores a file starting with $I for each item - var parentPath = Path.GetDirectoryName(source.Path) - ?? throw new InvalidOperationException("The recycle-bin item does not have a parent path."); - var fileName = Path.GetFileName(source.Path)!; - string iFilePath = Path.Combine(parentPath, fileName.Replace("$R", "$I", StringComparison.Ordinal)); - await ShellViewModel.GetFileFromPathAsync(iFilePath, cancellationToken) - .OnSuccess(iFile => (iFile ?? throw new InvalidOperationException($"The recycle-bin metadata file '{iFilePath}' could not be opened.")) - .DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); - } - fsProgress.ReportStatus(fsResult); - - if (fsResult) - { - await ShellViewModel.RemoveFileOrFolderAsync(source.Path); - - if (!permanently) - { - // Enumerate Recycle Bin - IEnumerable nameMatchItems, items = await StorageTrashBinService.GetAllRecycleBinFoldersAsync(); - - // Get name matching files - if (FileExtensionHelpers.IsShortcutOrUrlFile(source.Path)) // We need to check if it is a shortcut file - { - var parentPath = Path.GetDirectoryName(source.Path) - ?? throw new InvalidOperationException("The recycled shortcut does not have a parent path."); - var fileName = Path.GetFileNameWithoutExtension(source.Path)!; - nameMatchItems = items.Where((item) => item.FilePath == Path.Combine(parentPath, fileName)); - } - else - nameMatchItems = items.Where((item) => item.FilePath == source.Path); - - // Get newest file - ShellFileItem? item = nameMatchItems.OrderBy((item) => item.RecycleDate).FirstOrDefault(); - if (item is null) - return null; - - return new StorageHistory(FileOperationType.Recycle, source, StorageHelpers.FromPathAndType( - item.RecyclePath ?? throw new InvalidOperationException("The recycle-bin item does not have a recycle path."), - source.ItemType)); - } - - return new StorageHistory(FileOperationType.Delete, source, null); - } - else - { - // Stop at first error - return null; - } - } - - public Task RenameAsync(IStorageItem source, string newName, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - { - return RenameAsync(StorageHelpers.FromStorageItem(source) - ?? throw new InvalidOperationException("The storage item could not be converted for renaming."), newName, collision, progress, cancellationToken); - } - - public async Task RenameAsync( - IStorageItemWithPath source, - string newName, - NameCollisionOption collision, - IProgress progress, - CancellationToken cancellationToken, - bool asAdmin = false) - { - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress); - - fsProgress.Report(); - - if (Path.GetFileName(source.Path) == newName && collision == NameCollisionOption.FailIfExists) - { - fsProgress.ReportStatus(FileSystemStatusCode.AlreadyExists); - - return null; - } - - if (!string.IsNullOrWhiteSpace(newName) && - !FilesystemHelpers.ContainsRestrictedCharacters(newName) && - !FilesystemHelpers.ContainsRestrictedFileName(newName)) - { - var renamed = await source.ToStorageItemResult() - .OnSuccess(async (t) => - { - if (t is null) - throw new InvalidOperationException($"The item '{source.Path}' could not be opened for renaming."); - if (t.Name.Equals(newName, StringComparison.CurrentCultureIgnoreCase)) - await t.RenameAsync(newName, NameCollisionOption.ReplaceExisting); - else - await t.RenameAsync(newName, collision); - - return t; - }); - - if (renamed.Result is { } renamedItem) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - return new StorageHistory(FileOperationType.Rename, source, renamedItem.FromStorageItem()); - } - else if (renamed == FileSystemStatusCode.Unauthorized) - { - // Try again with MoveFileFromApp - var parentPath = Path.GetDirectoryName(source.Path) - ?? throw new InvalidOperationException("The item being renamed does not have a parent path."); - var destination = Path.Combine(parentPath, newName); - if (PInvoke.MoveFileFromApp(source.Path, destination)) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - return new StorageHistory(FileOperationType.Rename, source, StorageHelpers.FromPathAndType(destination, source.ItemType)); - } - else - { - // Cannot do anything, already tried with admin FTP - } - } - else if (renamed == FileSystemStatusCode.NotAFile || renamed == FileSystemStatusCode.NotAFolder) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.RenameErrorNameInvalidTitle.GetLocalizedResource(), Strings.RenameErrorNameInvalidText.GetLocalizedResource()); - } - else if (renamed == FileSystemStatusCode.NameTooLong) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.RenameErrorTooLongTitle.GetLocalizedResource(), Strings.RenameErrorTooLongText.GetLocalizedResource()); - } - else if (renamed == FileSystemStatusCode.InUse) - { - // TODO: Retry - await DialogDisplayHelper.ShowDialogAsync(DynamicDialogFactory.GetFor_FileInUseDialog()); - } - else if (renamed == FileSystemStatusCode.NotFound) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.RenameErrorItemDeletedTitle.GetLocalizedResource(), Strings.RenameErrorItemDeletedText.GetLocalizedResource()); - } - else if (renamed == FileSystemStatusCode.AlreadyExists) - { - var ItemAlreadyExistsDialog = new ContentDialog() - { - Title = Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), - Content = Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource(), - PrimaryButtonText = Strings.GenerateNewName.GetLocalizedResource(), - SecondaryButtonText = Strings.ItemAlreadyExistsDialogSecondaryButtonText.GetLocalizedResource(), - CloseButtonText = Strings.Cancel.GetLocalizedResource() - }; - - ContentDialogResult result = await ItemAlreadyExistsDialog.TryShowAsync(); - - if (result == ContentDialogResult.Primary) - { - return await RenameAsync(source, newName, NameCollisionOption.GenerateUniqueName, progress, cancellationToken); - } - else if (result == ContentDialogResult.Secondary) - { - return await RenameAsync(source, newName, NameCollisionOption.ReplaceExisting, progress, cancellationToken); - } - } - - fsProgress.ReportStatus(renamed); - } - - return null; - } - - public async Task RestoreItemsFromTrashAsync(IList source, IList destination, IProgress progress, CancellationToken cancellationToken) - { - return await RestoreItemsFromTrashAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for restoration.")).ToListAsync(), destination, progress, cancellationToken); - } - - public async Task RestoreItemsFromTrashAsync( - IList source, - IList destination, - IProgress progress, - CancellationToken token, - bool asAdmin = false) - { - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, source.Count); - fsProgress.Report(); - - var rawStorageHistory = new List(); - - for (int i = 0; i < source.Count; i++) - { - if (token.IsCancellationRequested) - break; - - rawStorageHistory.Add(await RestoreFromTrashAsync(source[i], destination[i], null, token)); - - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - - } - - if (rawStorageHistory.Count > 0 && rawStorageHistory.All(item => item is not null)) - { - var storageHistory = rawStorageHistory.WhereNotNull().ToList(); - return new StorageHistory( - storageHistory[0].OperationType, - await storageHistory.SelectMany(item => item.Source).ToListAsync(), - await storageHistory.SelectMany(item => item.Destination!).ToListAsync()); - } - - return null; - } - - public Task RestoreFromTrashAsync(IStorageItem source, string destination, IProgress? progress, CancellationToken cancellationToken) - { - return RestoreFromTrashAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for restoration."), destination, progress, cancellationToken); - } - - public async Task RestoreFromTrashAsync(IStorageItemWithPath source, string destination, IProgress? progress, CancellationToken cancellationToken) - { - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress); - fsProgress.Report(); - - FilesystemResult fsResult = FileSystemStatusCode.InProgress; - - fsResult = (FilesystemResult)(bool)await Task.Run(() => PInvoke.MoveFileFromApp(source.Path, destination)); - - if (!fsResult) - { - if (source.ItemType == FilesystemItemType.Directory) - { - FilesystemResult sourceFolder = await ShellViewModel.GetFolderFromPathAsync(source.Path, cancellationToken); - FilesystemResult destinationFolder = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination), cancellationToken); - - fsResult = sourceFolder.ErrorCode | destinationFolder.ErrorCode; - fsProgress.ReportStatus(fsResult); - - if (fsResult && - sourceFolder.Result is { } sourceFolderItem && - destinationFolder.Result is { } destinationFolderItem) - { - // Moving folders using Storage API can result in data loss, copy instead - //fsResult = await FilesystemTasks.Wrap(() => MoveDirectoryAsync(sourceFolder.Result, destinationFolder.Result, Path.GetFileName(destination), CreationCollisionOption.FailIfExists, true)); - - var destinationName = Path.GetFileName(destination)!; - if (await DialogDisplayHelper.ShowDialogAsync(Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), Strings.ErrorDialogUnsupportedMoveOperation.GetLocalizedResource(), "OK", Strings.Cancel.GetLocalizedResource())) - { - fsResult = await FilesystemTasks.Wrap(() => CloneDirectoryAsync(sourceFolderItem, destinationFolderItem, destinationName, CreationCollisionOption.FailIfExists)); - } - - // TODO: we could use here FilesystemHelpers with registerHistory false? - } - else if (fsResult) - { - fsResult = FileSystemStatusCode.Generic; - } - - fsProgress.ReportStatus(fsResult); - } - else - { - FilesystemResult sourceFile = await ShellViewModel.GetFileFromPathAsync(source.Path, cancellationToken); - FilesystemResult destinationFolder = await ShellViewModel.GetFolderFromPathAsync(PathNormalization.GetParentDir(destination), cancellationToken); - - fsResult = sourceFile.ErrorCode | destinationFolder.ErrorCode; - fsProgress.ReportStatus(fsResult); - - var destinationName = Path.GetFileName(destination)!; - if (fsResult && - sourceFile.Result is { } sourceFileItem && - destinationFolder.Result is { } destinationFolderItem) - { - fsResult = await FilesystemTasks.Wrap(() => sourceFileItem.MoveAsync(destinationFolderItem, destinationName, NameCollisionOption.GenerateUniqueName).AsTask()); - } - else if (fsResult) - { - fsResult = FileSystemStatusCode.Generic; - } - - fsProgress.ReportStatus(fsResult); - } - - if (fsResult == FileSystemStatusCode.Unauthorized || fsResult == FileSystemStatusCode.ReadOnly) - { - // Can't do anything, already tried with admin FTP - } - } - - if (fsResult) - { - // Recycle bin also stores a file starting with $I for each item - var parentPath = Path.GetDirectoryName(source.Path) - ?? throw new InvalidOperationException("The recycle-bin item does not have a parent path."); - var fileName = Path.GetFileName(source.Path)!; - string iFilePath = Path.Combine(parentPath, fileName.Replace("$R", "$I", StringComparison.Ordinal)); - await ShellViewModel.GetFileFromPathAsync(iFilePath, cancellationToken) - .OnSuccess(iFile => (iFile ?? throw new InvalidOperationException($"The recycle-bin metadata file '{iFilePath}' could not be opened.")) - .DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask()); - } - - fsProgress.ReportStatus(fsResult); - - if (fsResult != FileSystemStatusCode.Success) - { - if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.Unauthorized)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.AccessDenied.GetLocalizedResource(), Strings.AccessDeniedDeleteDialogText.GetLocalizedResource()); - } - else if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - } - else if (((FileSystemStatusCode)fsResult).HasFlag(FileSystemStatusCode.AlreadyExists)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource()); - } - } - - return new StorageHistory(FileOperationType.Restore, source, StorageHelpers.FromPathAndType(destination, source.ItemType)); - } - - private async static Task CloneDirectoryAsync(BaseStorageFolder sourceFolder, BaseStorageFolder destinationFolder, string sourceRootName, CreationCollisionOption collision = CreationCollisionOption.FailIfExists) - { - BaseStorageFolder createdRoot; - if (collision is CreationCollisionOption.ReplaceExisting) - // Dont't delete the contents of the folder - createdRoot = await destinationFolder.CreateFolderAsync(sourceRootName, CreationCollisionOption.OpenIfExists); - else - createdRoot = await destinationFolder.CreateFolderAsync(sourceRootName, collision); - - destinationFolder = createdRoot; - - foreach (BaseStorageFile fileInSourceDir in await sourceFolder.GetFilesAsync()) - { - await fileInSourceDir.CopyAsync(destinationFolder, fileInSourceDir.Name, collision.ConvertBack()); - } - - foreach (BaseStorageFolder folderinSourceDir in await sourceFolder.GetFoldersAsync()) - { - await CloneDirectoryAsync(folderinSourceDir, destinationFolder, folderinSourceDir.Name, collision); - } - - return createdRoot; - } - - public async Task CopyItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken) - { - return await CopyItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for copying.")).ToListAsync(), destination, collisions, progress, cancellationToken); - } - - public async Task CopyItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken token, bool asAdmin = false) - { - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, source.Count); - fsProgress.Report(); - - var rawStorageHistory = new List(); - - for (int i = 0; i < source.Count; i++) - { - if (token.IsCancellationRequested) - { - break; - } - - if (collisions[i] != FileNameConflictResolveOptionType.Skip) - { - rawStorageHistory.Add(await CopyAsync( - source[i], - destination[i], - collisions[i].Convert(), - null, - token)); - } - - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - - } - - if (rawStorageHistory.Count > 0 && rawStorageHistory.All(item => item is not null)) - { - var storageHistory = rawStorageHistory.WhereNotNull().ToList(); - return new StorageHistory( - storageHistory[0].OperationType, - await storageHistory.SelectMany(item => item.Source).ToListAsync(), - await storageHistory.SelectMany(item => item.Destination!).ToListAsync()); - } - return null; - } - - public async Task MoveItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken) - { - return await MoveItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for moving.")).ToListAsync(), destination, collisions, progress, cancellationToken); - } - - public async Task MoveItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken token, bool asAdmin = false) - { - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, source.Count); - fsProgress.Report(); - - var rawStorageHistory = new List(); - - for (int i = 0; i < source.Count; i++) - { - if (token.IsCancellationRequested) - { - break; - } - - if (collisions[i] != FileNameConflictResolveOptionType.Skip) - { - rawStorageHistory.Add(await MoveAsync( - source[i], - destination[i], - collisions[i].Convert(), - null, - token)); - } - - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - } - - if (rawStorageHistory.Count > 0 && rawStorageHistory.All(item => item is not null)) - { - var storageHistory = rawStorageHistory.WhereNotNull().ToList(); - return new StorageHistory( - storageHistory[0].OperationType, - await storageHistory.SelectMany(item => item.Source).ToListAsync(), - await storageHistory.SelectMany(item => item.Destination!).ToListAsync()); - } - return null; - } - - public async Task DeleteItemsAsync(IList source, IProgress? progress, bool permanently, CancellationToken cancellationToken) - { - return await DeleteItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for deletion.")).ToListAsync(), progress, permanently, cancellationToken); - } - - public async Task DeleteItemsAsync(IList source, IProgress? progress, bool permanently, CancellationToken token, bool asAdmin = false) - { - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, source.Count); - fsProgress.Report(); - - bool originalPermanently = permanently; - var rawStorageHistory = new List(); - - for (int i = 0; i < source.Count; i++) - { - if (token.IsCancellationRequested) - break; - - permanently = StorageTrashBinService.IsUnderTrashBin(source[i].Path) || originalPermanently; - - rawStorageHistory.Add(await DeleteAsync(source[i], null, permanently, token)); - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - } - - var storageHistory = rawStorageHistory.WhereNotNull().ToList(); - if (storageHistory.Count > 0) - { - // Permanent deletes cannot be undone, so only recycled items belong in a mixed batch's undo history. - var recycleHistory = storageHistory.Where(item => item.OperationType is FileOperationType.Recycle).ToList(); - if (recycleHistory.Count > 0) - { - if (recycleHistory.Any(item => item.Destination is null)) - return null; - - var sources = await recycleHistory.SelectMany(item => item.Source).ToListAsync(); - var destinations = await recycleHistory.SelectMany(item => item.Destination!).ToListAsync(); - - return sources.Count == destinations.Count - ? new StorageHistory(FileOperationType.Recycle, sources, destinations) - : null; - } - - return new StorageHistory( - FileOperationType.Delete, - await storageHistory.SelectMany(item => item.Source).ToListAsync(), - null); - } - return null; - } - - public Task CreateShortcutItemsAsync(IList source, IList destination, IProgress progress, CancellationToken token) - { - throw new NotImplementedException("Cannot create shortcuts in UWP."); - } - - public void Dispose() - { - _associatedInstance = null; - } - } -} diff --git a/src/Files.App/Utils/Storage/Operations/FilesystemOperationsFactory.cs b/src/Files.App/Utils/Storage/Operations/FilesystemOperationsFactory.cs index 8ef287cab0c2..87394564eb55 100644 --- a/src/Files.App/Utils/Storage/Operations/FilesystemOperationsFactory.cs +++ b/src/Files.App/Utils/Storage/Operations/FilesystemOperationsFactory.cs @@ -7,11 +7,7 @@ internal static class FilesystemOperationsFactory { public static IFilesystemOperations Create(IShellPage? associatedInstance) { -#if WINDOWS - return new ShellFilesystemOperations(associatedInstance!); -#else return new LinuxFilesystemOperations(associatedInstance); -#endif } } } diff --git a/src/Files.App/Utils/Storage/Operations/IFilesystemHelpers.cs b/src/Files.App/Utils/Storage/Operations/IFilesystemHelpers.cs index 23d960483131..8dda9ea1d3d2 100644 --- a/src/Files.App/Utils/Storage/Operations/IFilesystemHelpers.cs +++ b/src/Files.App/Utils/Storage/Operations/IFilesystemHelpers.cs @@ -18,29 +18,7 @@ public interface IFilesystemHelpers : IDisposable #region Delete -#if WINDOWS - /// - /// Deletes provided - /// - /// The to delete - /// Determines whether to show delete confirmation dialog - /// Determines whether is be deleted permanently - /// Determines whether is saved - /// of performed operation - Task DeleteItemsAsync(IEnumerable source, DeleteConfirmationPolicies showDialog, bool permanently, bool registerHistory); -#endif -#if WINDOWS - /// - /// Deletes provided - /// - /// The to delete - /// Determines whether to show delete confirmation dialog - /// Determines whether is be deleted permanently - /// Determines whether is saved - /// of performed operation - Task DeleteItemAsync(IStorageItem source, DeleteConfirmationPolicies showDialog, bool permanently, bool registerHistory); -#endif /// /// Deletes provided @@ -66,27 +44,7 @@ public interface IFilesystemHelpers : IDisposable #region Restore -#if WINDOWS - /// - /// Restores from the RecycleBin to fullPath - /// - /// The source Recycle Bin item path - /// The destination fullPath to restore to - /// Determines whether is saved - /// of performed operation - Task RestoreItemFromTrashAsync(IStorageItem source, string destination, bool registerHistory); -#endif -#if WINDOWS - /// - /// Restores from the RecycleBin to fullPath - /// - /// The source Recycle Bin item path - /// The destination fullPath to restore to - /// Determines whether is saved - /// of performed operation - Task RestoreItemsFromTrashAsync(IEnumerable source, IEnumerable destination, bool registerHistory); -#endif /// /// Restores from the RecycleBin to fullPath @@ -105,9 +63,7 @@ public interface IFilesystemHelpers : IDisposable /// Determines whether is saved /// of performed operation Task RestoreItemsFromTrashAsync(IEnumerable source, IEnumerable destination, bool registerHistory -#if !WINDOWS , Action? historyCallback = null -#endif ); #endregion Restore @@ -135,29 +91,7 @@ Task RestoreItemsFromTrashAsync(IEnumerable #region Copy -#if WINDOWS - /// - /// Copies to fullPath - /// - /// The source items to be copied - /// The destination fullPath - /// Determines whether to show copy dialog - /// Determines whether is saved - /// of performed operation - Task CopyItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory); -#endif -#if WINDOWS - /// - /// Copies to fullPath - /// - /// The source item to be copied - /// The destination fullPath - /// Determines whether to show copy dialog - /// Determines whether is saved - /// of performed operation - Task CopyItemAsync(IStorageItem source, string destination, bool showDialog, bool registerHistory); -#endif /// /// Copies to fullPath @@ -168,9 +102,7 @@ Task RestoreItemsFromTrashAsync(IEnumerable /// Determines whether is saved /// of performed operation Task CopyItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory -#if !WINDOWS , Action? historyCallback = null -#endif ); /// @@ -206,29 +138,7 @@ Task CopyItemsAsync(IEnumerable source, IEnu #region Move -#if WINDOWS - /// - /// Moves to fullPath - /// - /// The source items to be moved - /// The destination fullPath - /// Determines whether to show move dialog - /// Determines whether is saved - /// of performed operation - Task MoveItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory); -#endif -#if WINDOWS - /// - /// Moves to fullPath - /// - /// The source to move - /// The destination fullPath - /// Determines whether to show move dialog - /// Determines whether is saved - /// of performed operation - Task MoveItemAsync(IStorageItem source, string destination, bool showDialog, bool registerHistory); -#endif /// /// Moves to fullPath @@ -239,9 +149,7 @@ Task CopyItemsAsync(IEnumerable source, IEnu /// Determines whether is saved /// of performed operation Task MoveItemsAsync(IEnumerable source, IEnumerable destination, bool showDialog, bool registerHistory -#if !WINDOWS , Action? historyCallback = null -#endif ); /// @@ -271,18 +179,6 @@ Task MoveItemsAsync(IEnumerable source, IEnu #endregion Move -#if WINDOWS - /// - /// Renames with - /// - /// The item to rename - /// Desired new name - /// Determines what to do if item already exists - /// Determines whether is saved - /// Determines wheteher the Extension Modified Dialog is shown - /// of performed operation - Task RenameAsync(IStorageItem source, string newName, NameCollisionOption collision, bool registerHistory, bool showExtensionDialog = true); -#endif /// /// Renames fullPath with diff --git a/src/Files.App/Utils/Storage/Operations/IFilesystemOperations.cs b/src/Files.App/Utils/Storage/Operations/IFilesystemOperations.cs index 412c39e3becc..d7d3b53ee272 100644 --- a/src/Files.App/Utils/Storage/Operations/IFilesystemOperations.cs +++ b/src/Files.App/Utils/Storage/Operations/IFilesystemOperations.cs @@ -37,28 +37,6 @@ Task CreateShortcutItemsAsync( IProgress progress, CancellationToken cancellationToken); -#if WINDOWS - /// - /// Copies to fullPath - /// - /// The source item to be copied - /// The destination fullPath - /// The item naming collision - /// Progress of the operation - /// Can be cancelled with - /// where: - ///
- /// Source: The item fullPath (as ) - ///
- /// Destination: The item fullPath (as ) the was copied - ///
- Task CopyAsync( - IStorageItem source, - string destination, - NameCollisionOption collision, - IProgress progress, - CancellationToken cancellationToken); -#endif /// /// Copies to fullPath @@ -81,17 +59,6 @@ Task CreateShortcutItemsAsync( IProgress progress, CancellationToken cancellationToken); -#if WINDOWS - /// - /// Copies to fullPath - /// - Task CopyItemsAsync( - IList source, - IList destination, - IList collisions, - IProgress progress, - CancellationToken cancellationToken); -#endif /// /// Copies to fullPath @@ -104,28 +71,6 @@ Task CreateShortcutItemsAsync( CancellationToken cancellationToken, bool asAdmin = false); -#if WINDOWS - /// - /// Moves to fullPath - /// - /// The source item to be moved - /// The destination fullPath - /// The item naming collision - /// Progress of the operation - /// Can be cancelled with - /// where: - ///
- /// Source: The source item fullPath (as ) - ///
- /// Destination: The item fullPath (as ) the was moved - ///
- Task MoveAsync( - IStorageItem source, - string destination, - NameCollisionOption collision, - IProgress progress, - CancellationToken cancellationToken); -#endif /// /// Moves to fullPath @@ -148,17 +93,6 @@ Task CreateShortcutItemsAsync( IProgress progress, CancellationToken cancellationToken); -#if WINDOWS - /// - /// Moves to fullPath - /// - Task MoveItemsAsync( - IList source, - IList destination, - IList collisions, - IProgress progress, - CancellationToken cancellationToken); -#endif /// /// Moves to fullPath @@ -171,30 +105,6 @@ Task CreateShortcutItemsAsync( CancellationToken cancellationToken, bool asAdmin = false); -#if WINDOWS - /// - /// Deletes - /// - /// The source to delete - /// Progress of the operation - /// Determines whether is be deleted permanently - /// Can be cancelled with - /// where: - ///
- /// Source: The deleted item fullPath (as ) - ///
- /// Destination: - ///
- /// Returns null if was true - ///
- /// If was false, returns path to recycled item - ///
- Task DeleteAsync( - IStorageItem source, - IProgress progress, - bool permanently, - CancellationToken cancellationToken); -#endif /// /// Deletes @@ -219,16 +129,6 @@ Task CreateShortcutItemsAsync( bool permanently, CancellationToken cancellationToken); -#if WINDOWS - /// - /// Deletes provided - /// - Task DeleteItemsAsync( - IList source, - IProgress progress, - bool permanently, - CancellationToken cancellationToken); -#endif /// /// Deletes provided @@ -240,27 +140,6 @@ Task CreateShortcutItemsAsync( CancellationToken cancellationToken, bool asAdmin = false); -#if WINDOWS - /// - /// Renames with - /// - /// The item to rename - /// Desired new name - /// Determines what to do if item already exists - /// Can be cancelled with - /// where: - ///
- /// Source: The original item fullPath (as ) - ///
- /// Destination: The renamed item fullPath (as ) - ///
- Task RenameAsync( - IStorageItem source, - string newName, - NameCollisionOption collision, - IProgress progress, - CancellationToken cancellationToken); -#endif /// /// Renames fullPath with @@ -283,47 +162,7 @@ Task CreateShortcutItemsAsync( CancellationToken cancellationToken, bool asAdmin = false); -#if WINDOWS - /// - /// Restores from the RecycleBin to fullPath - /// - /// The source Recycle Bin item path - /// The destination fullPath to restore to - /// Progress of the operation - /// Can be cancelled with - /// where: - ///
- /// Source: The trash item fullPath - ///
- /// Destination: The item fullPath (as ) the has been restored - ///
- Task RestoreItemsFromTrashAsync( - IList source, - IList destination, - IProgress progress, - CancellationToken cancellationToken); -#endif -#if WINDOWS - /// - /// Restores from the RecycleBin to fullPath - /// - /// The source Recycle Bin item path - /// The destination fullPath to restore to - /// Progress of the operation - /// Can be cancelled with - /// where: - ///
- /// Source: The trash item fullPath - ///
- /// Destination: The item fullPath (as ) the has been restored - ///
- Task RestoreFromTrashAsync( - IStorageItem source, - string destination, - IProgress progress, - CancellationToken cancellationToken); -#endif /// /// Restores from the RecycleBin to fullPath diff --git a/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs b/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs index ee9fea0cbbf5..4a6b531396df 100644 --- a/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs +++ b/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs @@ -210,36 +210,18 @@ public async Task CreateShortcutItemsAsync(IList CopyAsync(IStorageItem source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - => CopyAsync(source.FromStorageItem() ?? throw new InvalidOperationException("The storage item could not be converted for copying."), destination, collision, progress, cancellationToken); -#endif public Task CopyAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) => CopyItemsAsync(source.CreateList(), destination.CreateList(), collision.ConvertBack().CreateList(), progress, cancellationToken); -#if WINDOWS - public async Task CopyItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken) - => await CopyItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for copying.")).ToListAsync(), destination, collisions, progress, cancellationToken); -#endif public Task CopyItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) => TransferAsync(false, source, destination, collisions, progress, cancellationToken); -#if WINDOWS - public Task MoveAsync(IStorageItem source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - => MoveAsync(source.FromStorageItem() ?? throw new InvalidOperationException("The storage item could not be converted for moving."), destination, collision, progress, cancellationToken); -#endif public Task MoveAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) => MoveItemsAsync(source.CreateList(), destination.CreateList(), collision.ConvertBack().CreateList(), progress, cancellationToken); -#if WINDOWS - public async Task MoveItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken) - => await MoveItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for moving.")).ToListAsync(), destination, collisions, progress, cancellationToken); -#endif public Task MoveItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) => TransferAsync(true, source, destination, collisions, progress, cancellationToken); @@ -363,19 +345,10 @@ public async Task CreateShortcutItemsAsync(IList DeleteAsync(IStorageItem source, IProgress progress, bool permanently, CancellationToken cancellationToken) - => DeleteAsync(source.FromStorageItem() ?? throw new InvalidOperationException("The storage item could not be converted for deletion."), progress, permanently, cancellationToken); -#endif public Task DeleteAsync(IStorageItemWithPath source, IProgress progress, bool permanently, CancellationToken cancellationToken) => DeleteItemsAsync(source.CreateList(), progress, permanently, cancellationToken); -#if WINDOWS - public async Task DeleteItemsAsync(IList source, IProgress progress, bool permanently, CancellationToken cancellationToken) - => await DeleteItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for deletion.")).ToListAsync(), progress, permanently, cancellationToken); -#endif public async Task DeleteItemsAsync(IList source, IProgress progress, bool permanently, CancellationToken cancellationToken, bool asAdmin = false) { @@ -466,10 +439,6 @@ public async Task CreateShortcutItemsAsync(IList s.Src).ToList(), null); } -#if WINDOWS - public Task RenameAsync(IStorageItem source, string newName, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - => RenameAsync(source.FromStorageItem() ?? throw new InvalidOperationException("The storage item could not be converted for renaming."), newName, collision, progress, cancellationToken); -#endif public async Task RenameAsync(IStorageItemWithPath source, string newName, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) { @@ -502,16 +471,7 @@ public async Task CreateShortcutItemsAsync(IList RestoreItemsFromTrashAsync(IList source, IList destination, IProgress progress, CancellationToken cancellationToken) - => RestoreItemsFromTrashAsync(source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for restoration.")).ToList(), destination, progress, cancellationToken); -#endif -#if WINDOWS - public Task RestoreFromTrashAsync(IStorageItem source, string destination, IProgress progress, CancellationToken cancellationToken) - => RestoreFromTrashAsync(source.FromStorageItem() ?? throw new InvalidOperationException("The storage item could not be converted for restoration."), destination, progress, cancellationToken); -#endif public Task RestoreFromTrashAsync(IStorageItemWithPath source, string destination, IProgress progress, CancellationToken cancellationToken) => RestoreItemsFromTrashAsync(source.CreateList(), destination.CreateList(), progress, cancellationToken); diff --git a/src/Files.App/Utils/Storage/Operations/ShellFilesystemOperations.Windows.cs b/src/Files.App/Utils/Storage/Operations/ShellFilesystemOperations.Windows.cs deleted file mode 100644 index fa783e2a66c1..000000000000 --- a/src/Files.App/Utils/Storage/Operations/ShellFilesystemOperations.Windows.cs +++ /dev/null @@ -1,958 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using Windows.Storage; - -namespace Files.App.Utils.Storage -{ - /// - /// Provides group of shell file system operation for given page instance. - /// - public sealed partial class ShellFilesystemOperations : IFilesystemOperations - { - private readonly IStorageTrashBinService StorageTrashBinService = Ioc.Default.GetRequiredService(); - - private readonly IShellPage _associatedInstance; - - private readonly FilesystemOperations _filesystemOperations; - - private ShellViewModel ShellViewModel => - _associatedInstance.GetRequiredShellViewModel(); - - public ShellFilesystemOperations(IShellPage associatedInstance) - { - _associatedInstance = associatedInstance; - _filesystemOperations = new FilesystemOperations(associatedInstance); - } - - public Task CopyAsync(IStorageItem source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - { - return CopyAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for copying."), destination, collision, progress, cancellationToken); - } - - public Task CopyAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - { - return CopyItemsAsync(source.CreateList(), destination.CreateList(), collision.ConvertBack().CreateList(), progress, cancellationToken); - } - - public async Task CopyItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken) - { - return await CopyItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for copying.")).ToListAsync(), destination, collisions, progress, cancellationToken); - } - - public async Task CopyItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) - { - if (source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x.Path) || ZipStorageFolder.IsZipPath(x.Path, false)) - || destination.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x) || ZipStorageFolder.IsZipPath(x, false))) - { - // Fallback to built-in file operations - return await _filesystemOperations.CopyItemsAsync(source, destination, collisions, progress, cancellationToken); - } - - StatusCenterItemProgressModel fsProgress = new( - progress, - false, - FileSystemStatusCode.InProgress, - source.Count); - - fsProgress.Report(); - - var sourceNoSkip = source.Zip(collisions, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.Skip).Select(item => item.src); - var destinationNoSkip = destination.Zip(collisions, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.Skip).Select(item => item.src); - var collisionsNoSkip = collisions.Where(c => c != FileNameConflictResolveOptionType.Skip); - - var operationID = Guid.NewGuid().ToString(); - - await using var r = cancellationToken.Register(CancelOperation, operationID, false); - - var sourceReplace = sourceNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll == FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var destinationReplace = destinationNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll == FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var sourceRename = sourceNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var destinationRename = destinationNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - - var result = (FilesystemResult)true; - var copyResult = new ShellOperationResult(); - - if (sourceRename.Any()) - { - var resultItem = await FileOperationsHelpers.CopyItemAsync(sourceRename.Select(s => s.Path).ToArray(), destinationRename.ToArray(), false, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, progress, operationID); - - result &= (FilesystemResult)resultItem.Item1; - - copyResult.Items.AddRange(resultItem.Item2?.Final ?? Enumerable.Empty()); - } - - if (sourceReplace.Any()) - { - var resultItem = await FileOperationsHelpers.CopyItemAsync(sourceReplace.Select(s => s.Path).ToArray(), destinationReplace.ToArray(), true, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, progress, operationID); - - result &= (FilesystemResult)resultItem.Item1; - - copyResult.Items.AddRange(resultItem.Item2?.Final ?? Enumerable.Empty()); - } - - result &= (FilesystemResult)copyResult.Items.All(x => x.Succeeded); - - if (result) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - var copiedSources = GetSuccessfulResults(copyResult.Items); - if (copiedSources.Any()) - { - var sourceMatch = await copiedSources.Select(x => sourceRename - .SingleOrDefault(s => s.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return new StorageHistory( - FileOperationType.Copy, - sourceMatch, - await copiedSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc }) - .Select(item => StorageHelpers.FromPathAndType(item.rSrc.Destination, item.oSrc.ItemType)).ToListAsync()); - } - - // Cannot undo overwrite operation - return null; - } - else - { - if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.Unauthorized)) - { - if (!asAdmin && await RequestAdminOperation()) - return await CopyItemsAsync(source, destination, collisions, progress, cancellationToken, true); - } - else if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse)) - { - var failedSources = copyResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse); - var filePath = failedSources.Select(x => x.HResult == CopyEngineResult.COPYENGINE_E_SHARING_VIOLATION_DEST ? x.Destination : x.Source).WhereNotNull(); - var lockingProcess = WhoIsLocking(filePath); - - switch (await GetFileInUseDialog(filePath, lockingProcess)) - { - case DialogResult.Primary: - var copyZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => copyZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await CopyItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - await sourceMatch.Select(x => x.coll).ToListAsync(), progress, cancellationToken); - } - } - else if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong)) - { - // Retry with the StorageFile API - var failedSources = copyResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong); - var copyZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => copyZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await _filesystemOperations.CopyItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - await sourceMatch.Select(x => x.coll).ToListAsync(), progress, cancellationToken); - } - else if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - } - else if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.AlreadyExists)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource()); - } - else if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.PropertyLoss)) - { - var failedSources = copyResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.PropertyLoss); - var filePath = failedSources.Select(x => x.Source).WhereNotNull(); - - switch (await GetFileListDialog(filePath, Strings.FilePropertiesCannotBeCopied.GetLocalizedResource(), Strings.CopyFileWithoutProperties.GetLocalizedResource(), Strings.OK.GetLocalizedResource(), Strings.Cancel.GetLocalizedResource())) - { - case DialogResult.Primary: - var copyZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => copyZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await CopyItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - // Force collision option to "replace" to accept copying with property loss - // Ok since property loss error is raised after checking if the destination already exists - await sourceMatch.Select(x => FileNameConflictResolveOptionType.ReplaceExisting).ToListAsync(), progress, cancellationToken); - } - } - else if (copyResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.FileTooLarge)) - { - var failingItems = copyResult.Items - .Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.FileTooLarge) - .Select(item => item.Source) - .WhereNotNull(); - - await Ioc.Default.GetRequiredService().ShowDialogAsync(new FileTooLargeDialogViewModel(failingItems.ToArray())); - } - // ADS - else if (copyResult.Items.All(x => x.HResult == -1)) - { - // Retry with the StorageFile API - var failedSources = copyResult.Items.Where(x => !x.Succeeded); - var copyZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => copyZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await _filesystemOperations.CopyItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - await sourceMatch.Select(x => x.coll).ToListAsync(), progress, cancellationToken); - } - - fsProgress.ReportStatus(CopyEngineResult.Convert(copyResult.Items.FirstOrDefault(x => !x.Succeeded)?.HResult)); - - return null; - } - } - - public async Task<(IStorageHistory?, IStorageItem?)> CreateAsync(IStorageItemWithPath source, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) - { - if (string.IsNullOrWhiteSpace(source.Path) || source.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(source.Path) || ZipStorageFolder.IsZipPath(source.Path, false)) - { - // Fallback to built-in file operations - return await _filesystemOperations.CreateAsync(source, progress, cancellationToken); - } - - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, 1); - fsProgress.Report(); - - var createResult = new ShellOperationResult(); - (var success, var response) = (false, new ShellOperationResult()); - - switch (source.ItemType) - { - case FilesystemItemType.File: - { - var newEntryInfo = await ShellNewEntryExtensions.GetNewContextMenuEntryForType(Path.GetExtension(source.Path)); - if (newEntryInfo?.Command is not null) - { - var args = CommandLineParser.SplitArguments(newEntryInfo.Command); - if (args.Any()) - { - if (await LaunchHelper.LaunchAppAsync( - args[0].Replace("\"", "", StringComparison.Ordinal), - string.Join(' ', args.Skip(1)).Replace("%1", source.Path), - PathNormalization.GetParentDir(source.Path))) - { - success = true; - } - } - } - else - { - (success, response) = await FileOperationsHelpers.CreateItemAsync(source.Path, "CreateFile", MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, newEntryInfo?.Template, newEntryInfo?.Data); - } - - break; - } - case FilesystemItemType.Directory: - { - (success, response) = await FileOperationsHelpers.CreateItemAsync(source.Path, "CreateFolder", MainWindow.Instance.WindowHandle.ToInt64(), asAdmin); - break; - } - } - - var result = (FilesystemResult)success; - var shellOpResult = response; - createResult.Items.AddRange(shellOpResult?.Final ?? Enumerable.Empty()); - - result &= (FilesystemResult)createResult.Items.All(x => x.Succeeded); - - if (result) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - var createdDestination = createResult.Items - .SingleOrDefault(x => x is { Succeeded: true, Destination: not null } && x.Source != x.Destination) - ?.Destination; - if (createdDestination is not null) - { - var item = StorageHelpers.FromPathAndType(createdDestination, source.ItemType); - var storageItem = await item.ToStorageItem(); - - return (new StorageHistory(FileOperationType.CreateNew, item.CreateList(), null), storageItem); - } - - return (null, null); - } - else - { - if (createResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.Unauthorized)) - { - if (!asAdmin && await RequestAdminOperation()) - return await CreateAsync(source, progress, cancellationToken, true); - } - else if (createResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong)) - { - // Retry with the StorageFile API - return await _filesystemOperations.CreateAsync(source, progress, cancellationToken); - } - else if (createResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - } - else if (createResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.AlreadyExists)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource()); - } - - fsProgress.ReportStatus(CopyEngineResult.Convert(createResult.Items.FirstOrDefault(x => !x.Succeeded)?.HResult)); - - return (null, null); - } - } - - public async Task CreateShortcutItemsAsync(IList source, IList destination, IProgress progress, CancellationToken cancellationToken) - { - var createdSources = new List(); - var createdDestination = new List(); - - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress, source.Count); - fsProgress.Report(); - - var items = source.Zip(destination, (src, dest) => new { src, dest }).Where(x => !string.IsNullOrEmpty(x.src.Path) && !string.IsNullOrEmpty(x.dest)); - foreach (var item in items) - { - var result = await FileOperationsHelpers.CreateOrUpdateLinkAsync(item.dest, item.src.Path); - - if (!result) - result = await UIFilesystemHelpers.HandleShortcutCannotBeCreated(Path.GetFileName(item.dest), item.src.Path); - - if (result) - { - createdSources.Add(item.src); - createdDestination.Add(StorageHelpers.FromPathAndType(item.dest, FilesystemItemType.File)); - } - - fsProgress.AddProcessedItemsCount(1); - fsProgress.Report(); - } - - fsProgress.ReportStatus(createdSources.Count == source.Count ? FileSystemStatusCode.Success : FileSystemStatusCode.Generic); - - return new StorageHistory(FileOperationType.CreateLink, createdSources, createdDestination); - } - - public Task DeleteAsync(IStorageItem source, IProgress progress, bool permanently, CancellationToken cancellationToken) - { - return DeleteAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for deletion."), progress, permanently, cancellationToken); - } - - public Task DeleteAsync(IStorageItemWithPath source, IProgress progress, bool permanently, CancellationToken cancellationToken) - { - return DeleteItemsAsync(source.CreateList(), progress, permanently, cancellationToken); - } - - public async Task DeleteItemsAsync(IList source, IProgress? progress, bool permanently, CancellationToken cancellationToken) - { - return await DeleteItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for deletion.")).ToListAsync(), progress, permanently, cancellationToken); - } - - public async Task DeleteItemsAsync(IList source, IProgress? progress, bool permanently, CancellationToken cancellationToken, bool asAdmin = false) - { - if (source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x.Path))) - { - // Fallback to built-in file operations - return await _filesystemOperations.DeleteItemsAsync(source, progress, permanently, cancellationToken); - } - - StatusCenterItemProgressModel fsProgress = new( - progress, - true, - FileSystemStatusCode.InProgress, - source.Count); - - fsProgress.Report(); - - var deleteFilePaths = source.Select(s => s.Path).Distinct(); - var deleteFromRecycleBin = source.Any() && StorageTrashBinService.IsUnderTrashBin(source.ElementAt(0).Path); - - permanently |= deleteFromRecycleBin; - - if (deleteFromRecycleBin) - { - // Recycle bin also stores a file starting with $I for each item - deleteFilePaths = deleteFilePaths.Concat(source.Select(x => GetRecycleMetadataPath(x.Path)).WhereNotNull()).Distinct(); - } - - var operationID = Guid.NewGuid().ToString(); - await using var r = cancellationToken.Register(CancelOperation, operationID, false); - - var (success, response) = await FileOperationsHelpers.DeleteItemAsync(deleteFilePaths.ToArray(), permanently, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, progress, operationID); - - var result = (FilesystemResult)success; - var deleteResult = new ShellOperationResult(); - deleteResult.Items.AddRange(response?.Final ?? Enumerable.Empty()); - - result &= (FilesystemResult)deleteResult.Items.All(x => x.Succeeded); - - if (result) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - foreach (var item in deleteResult.Items) - { - if (item.Source is { } itemPath) - await ShellViewModel.RemoveFileOrFolderAsync(itemPath); - } - - var recycledSources = GetSuccessfulResults(deleteResult.Items); - if (recycledSources.Any()) - { - var sourceMatch = await recycledSources.Select(x => source.DistinctBy(x => x.Path) - .SingleOrDefault(s => s.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return new StorageHistory( - FileOperationType.Recycle, - sourceMatch, - await recycledSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc }) - .Select(item => StorageHelpers.FromPathAndType(item.rSrc.Destination, item.oSrc.ItemType)).ToListAsync()); - } - - return new StorageHistory(FileOperationType.Delete, source, null); - } - else - { - if (deleteResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.Unauthorized)) - { - if (!asAdmin && await RequestAdminOperation()) - return await DeleteItemsAsync(source, progress, permanently, cancellationToken, true); - } - else if (deleteResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse)) - { - var failedSources = deleteResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse); - - var filesToCheck = new List(); - foreach (var failedSource in failedSources) - { - if (failedSource.Source is not { } failedPath) - continue; - - if (Directory.Exists(failedPath)) - { - try - { - var files = Directory.EnumerateFiles(failedPath, "*", SearchOption.AllDirectories); - filesToCheck.AddRange(files); - } - catch { } - } - else if (File.Exists(failedPath)) - { - filesToCheck.Add(failedPath); - } - } - - var filePath = filesToCheck.Any() ? filesToCheck : failedSources.Select(x => x.Source).WhereNotNull(); - var lockingProcess = WhoIsLocking(filePath); - - switch (await GetFileInUseDialog(filePath, lockingProcess)) - { - case DialogResult.Primary: - return await DeleteItemsAsync(await failedSources.Select(x => source.DistinctBy(x => x.Path).SingleOrDefault(s => s.Path == x.Source)).WhereNotNull().ToListAsync(), progress, permanently, cancellationToken); - } - } - else if (deleteResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong)) - { - // Abort, path is too long for recycle bin - } - else if (deleteResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - } - else if (deleteResult.Items.All(x => x.HResult == -1) && permanently) // ADS - { - // Retry with StorageFile API - var failedSources = deleteResult.Items.Where(x => !x.Succeeded); - var sourceMatch = await failedSources.Select(x => source.DistinctBy(x => x.Path).SingleOrDefault(s => s.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await _filesystemOperations.DeleteItemsAsync(sourceMatch, progress, permanently, cancellationToken); - } - - fsProgress.ReportStatus(CopyEngineResult.Convert(deleteResult.Items.FirstOrDefault(x => !x.Succeeded)?.HResult)); - - return null; - } - } - - public Task MoveAsync(IStorageItem source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - { - return MoveAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for moving."), destination, collision, progress, cancellationToken); - } - - public Task MoveAsync(IStorageItemWithPath source, string destination, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - { - return MoveItemsAsync(source.CreateList(), destination.CreateList(), collision.ConvertBack().CreateList(), progress, cancellationToken); - } - - public async Task MoveItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken) - { - return await MoveItemsAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for moving.")).ToListAsync(), destination, collisions, progress, cancellationToken); - } - - public async Task MoveItemsAsync(IList source, IList destination, IList collisions, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) - { - if (source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal)) || destination.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x) || ZipStorageFolder.IsZipPath(x, false))) - { - // Fallback to built-in file operations - return await _filesystemOperations.MoveItemsAsync(source, destination, collisions, progress, cancellationToken); - } - - StatusCenterItemProgressModel fsProgress = new( - progress, - true, - FileSystemStatusCode.InProgress, - source.Count); - - fsProgress.Report(); - - var sourceNoSkip = source.Zip(collisions, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.Skip).Select(item => item.src); - var destinationNoSkip = destination.Zip(collisions, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.Skip).Select(item => item.src); - var collisionsNoSkip = collisions.Where(c => c != FileNameConflictResolveOptionType.Skip); - var operationID = Guid.NewGuid().ToString(); - - await using var r = cancellationToken.Register(CancelOperation, operationID, false); - - var sourceReplace = sourceNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll == FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var destinationReplace = destinationNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll == FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var sourceRename = sourceNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var destinationRename = destinationNoSkip.Zip(collisionsNoSkip, (src, coll) => new { src, coll }).Where(item => item.coll != FileNameConflictResolveOptionType.ReplaceExisting).Select(item => item.src); - var result = (FilesystemResult)true; - var moveResult = new ShellOperationResult(); - - if (sourceRename.Any()) - { - var (status, response) = await FileOperationsHelpers.MoveItemAsync(sourceRename.Select(s => s.Path).ToArray(), destinationRename.ToArray(), false, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, progress, operationID); - - result &= (FilesystemResult)status; - moveResult.Items.AddRange(response?.Final ?? Enumerable.Empty()); - } - - if (sourceReplace.Any()) - { - var (status, response) = await FileOperationsHelpers.MoveItemAsync(sourceReplace.Select(s => s.Path).ToArray(), destinationReplace.ToArray(), true, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, progress, operationID); - - result &= (FilesystemResult)status; - moveResult.Items.AddRange(response?.Final ?? Enumerable.Empty()); - } - - result &= (FilesystemResult)moveResult.Items.All(x => x.Succeeded); - - if (result) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - var movedSources = GetSuccessfulResults(moveResult.Items); - if (movedSources.Any()) - { - var sourceMatch = await movedSources.Select(x => sourceRename - .SingleOrDefault(s => s.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return new StorageHistory(FileOperationType.Move, - sourceMatch, - await movedSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc }) - .Select(item => StorageHelpers.FromPathAndType(item.rSrc.Destination, item.oSrc.ItemType)).ToListAsync()); - } - - // Cannot undo overwrite operation - return null; - } - else - { - fsProgress.ReportStatus(CopyEngineResult.Convert(moveResult.Items.FirstOrDefault(x => !x.Succeeded)?.HResult)); - if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.Unauthorized)) - { - if (!asAdmin && await RequestAdminOperation()) - return await MoveItemsAsync(source, destination, collisions, progress, cancellationToken, true); - } - else if (source.Zip(destination, (src, dest) => (src, dest)).FirstOrDefault(x => x.src.ItemType == FilesystemItemType.Directory && PathNormalization.GetParentDir(x.dest).IsSubPathOf(x.src.Path)) is (IStorageItemWithPath, string) subtree) - { - var destName = subtree.dest.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); - var srcName = subtree.src.Path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).Last(); - - await DialogDisplayHelper.ShowDialogAsync(Strings.ErrorDialogThisActionCannotBeDone.GetLocalizedResource(), $"{Strings.ErrorDialogTheDestinationFolder.GetLocalizedResource()} ({destName}) {Strings.ErrorDialogIsASubfolder.GetLocalizedResource()} ({srcName})"); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse)) - { - var failedSources = moveResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse); - var filePath = failedSources.Select(x => x.HResult == CopyEngineResult.COPYENGINE_E_SHARING_VIOLATION_DEST ? x.Destination : x.Source).WhereNotNull(); - var lockingProcess = WhoIsLocking(filePath); - - switch (await GetFileInUseDialog(filePath, lockingProcess)) - { - case DialogResult.Primary: - var moveZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => moveZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await MoveItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - await sourceMatch.Select(x => x.coll).ToListAsync(), progress, cancellationToken); - } - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong)) - { - // Retry with the StorageFile API - var failedSources = moveResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong); - var moveZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => moveZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await _filesystemOperations.MoveItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - await sourceMatch.Select(x => x.coll).ToListAsync(), progress, cancellationToken); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.AlreadyExists)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource()); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.PropertyLoss)) - { - var failedSources = moveResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.PropertyLoss); - var filePath = failedSources.Select(x => x.Source).WhereNotNull(); - switch (await GetFileListDialog(filePath, Strings.FilePropertiesCannotBeMoved.GetLocalizedResource(), Strings.MoveFileWithoutProperties.GetLocalizedResource(), Strings.OK.GetLocalizedResource(), Strings.Cancel.GetLocalizedResource())) - { - case DialogResult.Primary: - var copyZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => copyZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - return await CopyItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - // Force collision option to "replace" to accept moving with property loss - // Ok since property loss error is raised after checking if the destination already exists - await sourceMatch.Select(x => FileNameConflictResolveOptionType.ReplaceExisting).ToListAsync(), progress, cancellationToken); - } - } - else if (moveResult.Items.All(x => x.HResult == -1)) // ADS - { - // Retry with the StorageFile API - var failedSources = moveResult.Items.Where(x => !x.Succeeded); - var moveZip = sourceNoSkip.Zip(destinationNoSkip, (src, dest) => new { src, dest }).Zip(collisionsNoSkip, (z1, coll) => new { z1.src, z1.dest, coll }); - var sourceMatch = await failedSources.Select(x => moveZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await _filesystemOperations.MoveItemsAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), - await sourceMatch.Select(x => x.coll).ToListAsync(), progress, cancellationToken); - } - - return null; - } - } - - public Task RenameAsync(IStorageItem source, string newName, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken) - { - return RenameAsync(StorageHelpers.FromStorageItem(source) - ?? throw new InvalidOperationException("The storage item could not be converted for renaming."), newName, collision, progress, cancellationToken); - } - - public async Task RenameAsync(IStorageItemWithPath source, string newName, NameCollisionOption collision, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) - { - if (string.IsNullOrWhiteSpace(source.Path) || source.Path.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(source.Path) || ZipStorageFolder.IsZipPath(source.Path, false)) - { - // Fallback to built-in file operations - return await _filesystemOperations.RenameAsync(source, newName, collision, progress, cancellationToken); - } - - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress); - fsProgress.Report(); - - var renameResult = new ShellOperationResult(); - var (status, response) = await FileOperationsHelpers.RenameItemAsync(source.Path, newName, collision == NameCollisionOption.ReplaceExisting, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin); - var result = (FilesystemResult)status; - - renameResult.Items.AddRange(response?.Final ?? Enumerable.Empty()); - - result &= (FilesystemResult)renameResult.Items.All(x => x.Succeeded); - - if (result) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - var renamedDestination = renameResult.Items - .SingleOrDefault(x => x is { Succeeded: true, Destination: not null } && - x.Source == source.Path && - x.Source != x.Destination) - ?.Destination; - if (renamedDestination is not null) - { - return new StorageHistory(FileOperationType.Rename, source, - StorageHelpers.FromPathAndType(renamedDestination, source.ItemType)); - } - - // Cannot undo overwrite operation - return null; - } - else - { - if (renameResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.Unauthorized)) - { - if (!asAdmin && await RequestAdminOperation()) - { - var res = await RenameAsync(source, newName, collision, progress, cancellationToken, true); - if (res is null) - { - await DynamicDialogFactory - .GetFor_RenameRequiresHigherPermissions(source.Path) - .TryShowAsync(); - } - - return res; - } - } - else if (renameResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse)) - { - var failedSources = renameResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse); - var filePath = failedSources.Select(x => x.HResult == CopyEngineResult.COPYENGINE_E_SHARING_VIOLATION_DEST ? x.Destination : x.Source).WhereNotNull(); - var lockingProcess = WhoIsLocking(filePath); - - switch (await GetFileInUseDialog(filePath, lockingProcess)) - { - case DialogResult.Primary: - return await RenameAsync(source, newName, collision, progress, cancellationToken); - } - } - else if (renameResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong)) - { - // Retry with the StorageFile API - return await _filesystemOperations.RenameAsync(source, newName, collision, progress, cancellationToken); - } - else if (renameResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.RenameErrorItemDeletedTitle.GetLocalizedResource(), Strings.RenameErrorItemDeletedText.GetLocalizedResource()); - } - else if (renameResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.AlreadyExists)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource()); - } - // ADS - else if (renameResult.Items.All(x => x.HResult == -1)) - { - // Retry with StorageFile API - return await _filesystemOperations.RenameAsync(source, newName, collision, progress, cancellationToken); - } - - fsProgress.ReportStatus(CopyEngineResult.Convert(renameResult.Items.FirstOrDefault(x => !x.Succeeded)?.HResult)); - - return null; - } - } - - public Task RestoreFromTrashAsync(IStorageItem source, string destination, IProgress progress, CancellationToken cancellationToken) - { - return RestoreFromTrashAsync(source.FromStorageItem() - ?? throw new InvalidOperationException("The storage item could not be converted for restoration."), destination, progress, cancellationToken); - } - - public Task RestoreFromTrashAsync(IStorageItemWithPath source, string destination, IProgress progress, CancellationToken cancellationToken) - { - return RestoreItemsFromTrashAsync(source.CreateList(), destination.CreateList(), progress, cancellationToken); - } - - public async Task RestoreItemsFromTrashAsync(IList source, IList destination, IProgress progress, CancellationToken cancellationToken) - { - return await RestoreItemsFromTrashAsync(await source.Select(item => item.FromStorageItem() - ?? throw new InvalidOperationException("A storage item could not be converted for restoration.")).ToListAsync(), destination, progress, cancellationToken); - } - - public async Task RestoreItemsFromTrashAsync(IList source, IList destination, IProgress progress, CancellationToken cancellationToken, bool asAdmin = false) - { - if (source.Any(x => string.IsNullOrWhiteSpace(x.Path) || x.Path.StartsWith(@"\\?\", StringComparison.Ordinal)) || destination.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith(@"\\?\", StringComparison.Ordinal) || FtpHelpers.IsFtpPath(x) || ZipStorageFolder.IsZipPath(x, false))) - { - // Fallback to built-in file operations - return await _filesystemOperations.RestoreItemsFromTrashAsync(source, destination, progress, cancellationToken); - } - - StatusCenterItemProgressModel fsProgress = new(progress, true, FileSystemStatusCode.InProgress); - fsProgress.Report(); - var operationID = Guid.NewGuid().ToString(); - await using var r = cancellationToken.Register(CancelOperation, operationID, false); - - var moveResult = new ShellOperationResult(); - var (status, response) = await FileOperationsHelpers.MoveItemAsync(source.Select(s => s.Path).ToArray(), [.. destination], false, MainWindow.Instance.WindowHandle.ToInt64(), asAdmin, progress, operationID); - - var result = (FilesystemResult)status; - moveResult.Items.AddRange(response?.Final ?? Enumerable.Empty()); - - result &= (FilesystemResult)moveResult.Items.All(x => x.Succeeded); - - if (result) - { - fsProgress.ReportStatus(FileSystemStatusCode.Success); - - var movedSources = GetSuccessfulResults(moveResult.Items); - if (movedSources.Any()) - { - var sourceMatch = await movedSources.Select(x => source - .SingleOrDefault(s => s.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - // Recycle bin also stores a file starting with $I for each item - await DeleteItemsAsync(await movedSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc }) - .Select(src => StorageHelpers.FromPathAndType( - GetRecycleMetadataPath(src.rSrc.Source) ?? throw new InvalidOperationException("The recycle bin metadata path is invalid."), - src.oSrc.ItemType)).ToListAsync(), null, true, cancellationToken); - - return new StorageHistory(FileOperationType.Restore, - sourceMatch, - await movedSources.Zip(sourceMatch, (rSrc, oSrc) => new { rSrc, oSrc }) - .Select(item => StorageHelpers.FromPathAndType(item.rSrc.Destination, item.oSrc.ItemType)).ToListAsync()); - } - // Cannot undo overwrite operation - return null; - } - else - { - if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.Unauthorized)) - { - if (!asAdmin && await RequestAdminOperation()) - return await RestoreItemsFromTrashAsync(source, destination, progress, cancellationToken, true); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse)) - { - var failedSources = moveResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.InUse); - var filePath = failedSources.Select(x => x.HResult == CopyEngineResult.COPYENGINE_E_SHARING_VIOLATION_DEST ? x.Destination : x.Source).WhereNotNull(); - var lockingProcess = WhoIsLocking(filePath); - - switch (await GetFileInUseDialog(filePath, lockingProcess)) - { - case DialogResult.Primary: - var moveZip = source.Zip(destination, (src, dest) => new { src, dest }); - var sourceMatch = await failedSources.Select(x => moveZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await RestoreItemsFromTrashAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), progress, cancellationToken); - } - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong)) - { - // Retry with StorageFile API - var failedSources = moveResult.Items.Where(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NameTooLong); - var moveZip = source.Zip(destination, (src, dest) => new { src, dest }); - var sourceMatch = await failedSources.Select(x => moveZip.SingleOrDefault(s => s.src.Path.Equals(x.Source, StringComparison.OrdinalIgnoreCase))).WhereNotNull().ToListAsync(); - - return await _filesystemOperations.RestoreItemsFromTrashAsync( - await sourceMatch.Select(x => x.src).ToListAsync(), - await sourceMatch.Select(x => x.dest).ToListAsync(), progress, cancellationToken); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.NotFound)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.FileNotFoundDialogTitle.GetLocalizedResource(), Strings.FileNotFoundDialogText.GetLocalizedResource()); - } - else if (moveResult.Items.Any(x => CopyEngineResult.Convert(x.HResult) == FileSystemStatusCode.AlreadyExists)) - { - await DialogDisplayHelper.ShowDialogAsync(Strings.ItemAlreadyExistsDialogTitle.GetLocalizedResource(), Strings.ItemAlreadyExistsDialogContent.GetLocalizedResource()); - } - - fsProgress.ReportStatus(CopyEngineResult.Convert(moveResult.Items.FirstOrDefault(x => !x.Succeeded)?.HResult)); - - return null; - } - } - - private void CancelOperation(object? operationID) - { - if (operationID is string id) - FileOperationsHelpers.TryCancelOperation(id); - } - - private async Task RequestAdminOperation() - { - var dialogService = Ioc.Default.GetRequiredService(); - return await dialogService.ShowDialogAsync(new ElevateConfirmDialogViewModel()) == DialogResult.Primary; - } - - private Task GetFileInUseDialog(IEnumerable source, IEnumerable lockingProcess) - { - var titleText = Strings.FileInUseDialogTitle.GetLocalizedResource(); - var subtitleText = lockingProcess.IsEmpty() - ? Strings.FileInUseDialogText.GetLocalizedResource() - : string.Format(Strings.FileInUseByDialogText.GetLocalizedResource(), string.Join(", ", lockingProcess.Select(x => $"{x.AppName ?? x.Name} (PID: {x.Pid})"))); - - var sourceCount = source.Count(); - - return GetFileListDialog( - source, - titleText, - subtitleText, - Strings.Retry.GetLocalizedResource(), - sourceCount > 1 ? Strings.Skip.GetLocalizedResource() : Strings.Cancel.GetLocalizedResource()); - } - - private async Task GetFileListDialog(IEnumerable source, string titleText, string? descriptionText = null, string? primaryButtonText = null, string? secondaryButtonText = null, string? closeButtonText = null) - { - var incomingItems = new List(); - List? binItems = null; - foreach (var src in source) - { - if (StorageTrashBinService.IsUnderTrashBin(src)) - { - binItems ??= await StorageTrashBinService.GetAllRecycleBinFoldersAsync(); - - // Might still be null because we're deserializing the list from Json - if (!binItems.IsEmpty()) - { - // Get original file name - var matchingItem = binItems.FirstOrDefault(x => x.RecyclePath == src); - - incomingItems.Add(new FileSystemDialogDefaultItemViewModel() { SourcePath = src, DisplayName = matchingItem?.FileName }); - } - } - else - { - incomingItems.Add(new FileSystemDialogDefaultItemViewModel() { SourcePath = src }); - } - } - - var dialogViewModel = FileSystemDialogViewModel.GetDialogViewModel( - incomingItems, titleText, descriptionText, primaryButtonText, secondaryButtonText, closeButtonText); - - var dialogService = Ioc.Default.GetRequiredService(); - - return await dialogService.ShowDialogAsync(dialogViewModel); - } - - private IEnumerable WhoIsLocking(IEnumerable filesToCheck) - { - return FileOperationsHelpers.CheckFileInUse(filesToCheck.ToArray()) ?? []; - } - - private static IEnumerable<(ShellOperationItemResult Result, string Source, string Destination)> GetSuccessfulResults(IEnumerable results) - { - foreach (var result in results) - { - if (result is { Succeeded: true, Source: { } source, Destination: { } destination } && - source != destination) - { - yield return (result, source, destination); - } - } - } - - private static string? GetRecycleMetadataPath(string recyclePath) - { - var parentPath = Path.GetDirectoryName(recyclePath); - var fileName = Path.GetFileName(recyclePath); - - return parentPath is not null && !string.IsNullOrEmpty(fileName) - ? Path.Combine(parentPath, fileName.Replace("$R", "$I", StringComparison.Ordinal)) - : null; - } - - public void Dispose() - { - _filesystemOperations.Dispose(); - } - } -} diff --git a/src/Files.App/Utils/Storage/Search/FolderSearch.Linux.cs b/src/Files.App/Utils/Storage/Search/FolderSearch.Linux.cs index 543bf6b69b4d..d72864927c3d 100644 --- a/src/Files.App/Utils/Storage/Search/FolderSearch.Linux.cs +++ b/src/Files.App/Utils/Storage/Search/FolderSearch.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Search; using Microsoft.Extensions.Logging; using System.IO; @@ -182,4 +181,3 @@ private static ListedItem CreateLinuxItem(string path, bool isDirectory, long le } } } -#endif diff --git a/src/Files.App/Utils/Storage/Search/FolderSearch.Windows.cs b/src/Files.App/Utils/Storage/Search/FolderSearch.Windows.cs deleted file mode 100644 index fbec1b502eb3..000000000000 --- a/src/Files.App/Utils/Storage/Search/FolderSearch.Windows.cs +++ /dev/null @@ -1,563 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using Microsoft.Extensions.Logging; -using System.IO; -using System.IO.Enumeration; -using System.Text.RegularExpressions; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Search; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; -using FileAttributes = System.IO.FileAttributes; - -namespace Files.App.Utils.Storage -{ - public sealed partial class FolderSearch - { - private async Task SearchAsync(BaseStorageFolder folder, IList results, CancellationToken token) - { - uint index = 0; - var stepSize = Math.Min(defaultStepSize, GetRemainingItemCount(results)); - if (stepSize == 0) - return; - - var options = ToQueryOptions(); - - var queryResult = folder.CreateItemQueryWithOptions(options); - var items = await queryResult.GetItemsAsync(0, stepSize).AsTask(token); - - while (items.Count > 0) - { - foreach (IStorageItem item in items) - { - if (token.IsCancellationRequested) - { - return; - } - - try - { - if (!item.Name.StartsWith('.') || UserSettingsService.FoldersSettingsService.ShowDotFiles) - { - var listedItem = await GetListedItemAsync(item); - AddResult(results, listedItem, token); - if (listedItem.ItemPath is not null) - indexedResultPaths.Add(listedItem.ItemPath); - } - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Error creating ListedItem from StorageItem"); - } - } - - index += (uint)items.Count; - stepSize = Math.Min(defaultStepSize, GetRemainingItemCount(results)); - if (stepSize == 0) - return; - - items = await queryResult.GetItemsAsync(index, stepSize).AsTask(token); - } - } - - private async Task SearchTagsAsync(string folder, IList results, CancellationToken token) - { - var expression = ParseTagQuery(AQSQuery); - - if (expression.OrGroups.Count == 0) - { - return; - } - - var dbInstance = FileTagsHelper.GetDbInstance(); - var matches = dbInstance.GetAllUnderPath(folder) - .Where(x => MatchesTagExpression(x.Tags, expression)); - if (string.IsNullOrEmpty(folder)) - matches = matches.Where(x => !StorageTrashBinService.IsUnderTrashBin(x.FilePath)); - - foreach (var match in matches) - { - if (token.IsCancellationRequested) - return; - - (FindCloseSafeHandle? hFile, WIN32_FIND_DATAW findData) = await Task.Run(() => - { - WIN32_FIND_DATAW findDataTsk = default; - FindCloseSafeHandle hFileTsk; - unsafe - { - hFileTsk = PInvoke.FindFirstFileEx(match.FilePath, FINDEX_INFO_LEVELS.FindExInfoBasic, - &findDataTsk, FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - } - return (hFileTsk, findDataTsk); - }).WithTimeoutAsync(TimeSpan.FromSeconds(5)); - if (token.IsCancellationRequested) - { - hFile?.Dispose(); - return; - } - - if (hFile is { IsInvalid: false } tagSearchHandle) - { - using (tagSearchHandle) - { - string fileName = findData.cFileName.ToString(); - var isSystem = ((FileAttributes)findData.dwFileAttributes & FileAttributes.System) == FileAttributes.System; - var isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - var startWithDot = fileName.StartsWith('.'); - - bool shouldBeListed = (!isHidden || - (UserSettingsService.FoldersSettingsService.ShowHiddenItems && - (!isSystem || UserSettingsService.FoldersSettingsService.ShowProtectedSystemFiles))) && - (!startWithDot || UserSettingsService.FoldersSettingsService.ShowDotFiles); - - if (shouldBeListed) - { - var item = GetListedItemAsync(match.FilePath, findData); - if (item is not null) - AddResult(results, item, token); - } - } - } - else - { - hFile?.Dispose(); - try - { - IStorageItem? item = (await GetStorageFileAsync(match.FilePath)).Result; - item ??= (await GetStorageFolderAsync(match.FilePath)).Result; - item = item - ?? throw new InvalidOperationException($"The search item '{match.FilePath}' could not be opened."); - if (!item.Name.StartsWith('.') || UserSettingsService.FoldersSettingsService.ShowDotFiles) - { - AddResult(results, await GetListedItemAsync(item), token); - } - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Error creating ListedItem from StorageItem"); - } - } - } - } - - private async Task AddItemsAsync(string folder, IList results, CancellationToken token) - { - if (IsTagQuery(AQSQuery)) - { - await SearchTagsAsync(folder, results, token); - } - else - { - var workingFolder = await GetStorageFolderAsync(folder); - var storageFolder = workingFolder ? workingFolder.Result : null; - - if (IsAQSQuery) - { - if (storageFolder is not null) - await SearchAsync(storageFolder, results, token); - - return; - } - - if (storageFolder is SystemStorageFolder && !DriveHelpers.IsMtpPath(folder) && !await IsFullyIndexedAsync(storageFolder)) - { - await SearchWithWin32Async(folder, false, results, token); - return; - } - - var hiddenOnlyFromWin32 = false; - if (storageFolder is not null) - { - var countBefore = results.Count; - await SearchAsync(storageFolder, results, token); - hiddenOnlyFromWin32 = results.Count != countBefore; - } - - await SearchWithWin32Async(folder, hiddenOnlyFromWin32, results, token); - } - } - - private static async Task IsFullyIndexedAsync(BaseStorageFolder folder) - { - try - { - return await folder.GetIndexedStateAsync() == IndexedState.FullyIndexed; - } - catch (Exception) - { - return false; - } - } - - private Task SearchWithWin32Async(string folder, bool hiddenOnly, IList results, CancellationToken token) - { - return Task.Factory.StartNew( - () => SearchWithWin32(folder, hiddenOnly, results, token), - token, - TaskCreationOptions.LongRunning, - TaskScheduler.Default) - .WaitAsync(token); - } - - private void SearchWithWin32(string root, bool hiddenOnly, IList results, CancellationToken token) - { - var expression = FileSystemName.TranslateWin32Expression($"*{QueryWithWildcard}"); - var showHiddenItems = UserSettingsService.FoldersSettingsService.ShowHiddenItems; - var showProtectedSystemFiles = UserSettingsService.FoldersSettingsService.ShowProtectedSystemFiles; - var showDotFiles = UserSettingsService.FoldersSettingsService.ShowDotFiles; - - var pendingFolders = new Queue<(string Path, bool UseFindTimeout)>(); - pendingFolders.Enqueue((root, RequiresFindTimeout(root))); - - while (pendingFolders.TryDequeue(out var pendingFolder)) - { - var (folder, useFindTimeout) = pendingFolder; - if (token.IsCancellationRequested || results.Count >= UsedMaxItemCount) - return; - - using (var findHandle = FindFirstFile(folder, useFindTimeout, out var findData, token)) - { - if (findHandle is null || findHandle.IsInvalid) - continue; - - do - { - var fileName = findData.cFileName.ToString(); - if (fileName is "." or "..") - continue; - - var attributes = (FileAttributes)findData.dwFileAttributes; - var isDirectory = attributes.HasFlag(FileAttributes.Directory); - var reparseTag = attributes.HasFlag(FileAttributes.ReparsePoint) ? findData.dwReserved0 : 0; - - if (isDirectory && !IsNameSurrogateReparseTag(reparseTag)) - pendingFolders.Enqueue((Path.Combine(folder, fileName), useFindTimeout || IsCloudFilesReparseTag(reparseTag))); - - if (!FileSystemName.MatchesWin32Expression(expression, fileName)) - continue; - - var isSystem = attributes.HasFlag(FileAttributes.System); - var isHidden = attributes.HasFlag(FileAttributes.Hidden); - var startWithDot = fileName.StartsWith('.'); - var isShortcut = !isDirectory && FileExtensionHelpers.IsShortcutOrUrlFile(fileName); - - bool shouldBeListed = (hiddenOnly ? - (!isHidden && isShortcut) || (isHidden && showHiddenItems && (!isSystem || showProtectedSystemFiles)) : - !isHidden || (showHiddenItems && (!isSystem || showProtectedSystemFiles))) && - (!startWithDot || showDotFiles); - - var itemPath = Path.Combine(folder, fileName); - if (!shouldBeListed || (hiddenOnly && indexedResultPaths.Contains(itemPath))) - continue; - - try - { - if ((isShortcut ? GetShortcutItem(itemPath, findData) : GetListedItemAsync(itemPath, findData)) is { } item) - AddResult(results, item, token); - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, "Error creating ListedItem from Win32 find data"); - } - } - while (!token.IsCancellationRequested && results.Count < UsedMaxItemCount && PInvoke.FindNextFile(findHandle, out findData)); - } - - RaiseSearchTickIfDue(token); - } - } - - private static FindCloseSafeHandle? FindFirstFile(string folder, bool useTimeout, out WIN32_FIND_DATAW findData, CancellationToken token) - { - if (!useTimeout) - return FindFirstFile(folder, out findData); - - var findTask = Task.Run(() => (Handle: FindFirstFile(folder, out var data), Data: data)); - try - { - if (findTask.Wait(TimeSpan.FromSeconds(5), token)) - { - (var handle, findData) = findTask.Result; - return handle; - } - } - catch (OperationCanceledException) - { - } - - _ = findTask.ContinueWith(t => t.Result.Handle.Dispose(), TaskContinuationOptions.OnlyOnRanToCompletion); - findData = default; - return null; - } - - private static unsafe FindCloseSafeHandle FindFirstFile(string folder, out WIN32_FIND_DATAW findData) - { - WIN32_FIND_DATAW data = default; - var handle = PInvoke.FindFirstFileEx(Path.Join(folder, "*"), FINDEX_INFO_LEVELS.FindExInfoBasic, - &data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - findData = data; - return handle; - } - - private static bool RequiresFindTimeout(string root) - { - if (DriveHelpers.IsNetworkPath(root)) - return true; - - try - { - // Virtual cloud drives such as Google Drive report Fixed but aren't NTFS - var drive = new DriveInfo(root); - return drive.DriveType is not System.IO.DriveType.Fixed - || drive.DriveFormat is not ("NTFS" or "ReFS") - || File.GetAttributes(root).HasFlag(FileAttributes.ReparsePoint); - } - catch (Exception) - { - return true; - } - } - - // Junctions, symlinks and mount points - private static bool IsNameSurrogateReparseTag(uint reparseTag) - => (reparseTag & 0x20000000) != 0; - - // IO_REPARSE_TAG_CLOUD and IO_REPARSE_TAG_CLOUD_1 to _F - private static bool IsCloudFilesReparseTag(uint reparseTag) - => (reparseTag & 0xFFFF0FFF) == 0x9000001A; - - private static ShortcutItem GetShortcutItem(string itemPath, WIN32_FIND_DATAW findData) - { - string fileName = findData.cFileName.ToString(); - var isUrl = FileExtensionHelpers.IsWebLinkFile(fileName); - var isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - PInvoke.FileTimeToSystemTime(findData.ftLastWriteTime, out SYSTEMTIME modifiedTime); - PInvoke.FileTimeToSystemTime(findData.ftCreationTime, out SYSTEMTIME createdTime); - var fileSize = Win32FindDataExtensions.GetSize(findData); - - return new ShortcutItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = fileName.Contains('.', StringComparison.Ordinal) ? Path.GetExtension(itemPath)! : string.Empty, - IsHiddenItem = isHidden, - Opacity = isHidden ? Constants.UI.DimItemOpacity : 1, - FileImage = null, - LoadFileIcon = false, - ItemNameRaw = fileName, - ItemDateModifiedReal = modifiedTime.ToDateTime(), - ItemDateCreatedReal = createdTime.ToDateTime(), - ItemType = isUrl ? Strings.ShortcutWebLinkFileType.GetLocalizedResource() : Strings.Shortcut.GetLocalizedResource(), - ItemPath = itemPath, - FileSize = fileSize.ToSizeString(), - FileSizeBytes = fileSize, - IsUrl = isUrl, - }; - } - - private ListedItem? GetListedItemAsync(string itemPath, WIN32_FIND_DATAW findData) - { - string fileName = findData.cFileName.ToString(); - ListedItem? listedItem = null; - var isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - var isFolder = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory; - PInvoke.FileTimeToSystemTime(findData.ftLastWriteTime, out SYSTEMTIME systemModifiedTimeOutput); - PInvoke.FileTimeToSystemTime(findData.ftCreationTime, out SYSTEMTIME systemCreatedTimeOutput); - - if (!isFolder) - { - string? itemFileExtension = null; - string? itemType = null; - long fileSize = Win32FindDataExtensions.GetSize(findData); - if (fileName.Contains('.', StringComparison.Ordinal)) - { - itemFileExtension = Path.GetExtension(itemPath); - itemType = itemFileExtension!.Trim('.') + " " + itemType; - } - - listedItem = new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - ItemNameRaw = fileName, - ItemPath = itemPath, - ItemDateModifiedReal = systemModifiedTimeOutput.ToDateTime(), - ItemDateCreatedReal = systemCreatedTimeOutput.ToDateTime(), - IsHiddenItem = isHidden, - LoadFileIcon = false, - FileExtension = itemFileExtension, - ItemType = itemType, - Opacity = isHidden ? Constants.UI.DimItemOpacity : 1, - FileSize = fileSize.ToSizeString(), - FileSizeBytes = fileSize, - }; - } - else - { - if (fileName != "." && fileName != "..") - { - listedItem = new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = fileName, - ItemPath = itemPath, - ItemDateModifiedReal = systemModifiedTimeOutput.ToDateTime(), - ItemDateCreatedReal = systemCreatedTimeOutput.ToDateTime(), - IsHiddenItem = isHidden, - LoadFileIcon = false, - ItemType = folderTypeTextLocalized, - Opacity = isHidden ? Constants.UI.DimItemOpacity : 1 - }; - } - } - - return listedItem; - } - - private async Task GetListedItemAsync(IStorageItem item) - { - ListedItem? listedItem = null; - if (item.IsOfType(StorageItemTypes.Folder)) - { - var folder = item.AsBaseStorageFolder() - ?? throw new InvalidOperationException($"The search result '{item.Path}' could not be opened as a folder."); - - var props = await folder.GetBasicPropertiesAsync(); - if (folder is BinStorageFolder binFolder) - { - listedItem = new RecycleBinItem(null) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = folder.DisplayName, - ItemPath = folder.Path, - ItemDateModifiedReal = props.DateModified, - ItemDateCreatedReal = folder.DateCreated, - ItemType = folderTypeTextLocalized, - Opacity = 1, - FileSize = props.Size.ToSizeString(), - FileSizeBytes = (long)props.Size, - ItemDateDeletedReal = binFolder.DateDeleted, - ItemOriginalPath = binFolder.OriginalPath - }; - } - else - { - listedItem = new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemNameRaw = folder.DisplayName, - ItemPath = folder.Path, - ItemDateModifiedReal = props.DateModified, - ItemDateCreatedReal = folder.DateCreated, - ItemType = folderTypeTextLocalized, - Opacity = 1 - }; - } - } - else if (item.IsOfType(StorageItemTypes.File)) - { - var file = item.AsBaseStorageFile() - ?? throw new InvalidOperationException($"The search result '{item.Path}' could not be opened as a file."); - - var props = await file.GetBasicPropertiesAsync(); - string? itemFileExtension = null; - string? itemType = null; - if (file.Name.Contains('.', StringComparison.Ordinal)) - { - itemFileExtension = Path.GetExtension(file.Path); - itemType = itemFileExtension!.Trim('.') + " " + itemType; - } - - var itemSize = props.Size.ToSizeString(); - - if (file is BinStorageFile binFile) - { - listedItem = new RecycleBinItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - ItemNameRaw = file.Name, - ItemPath = file.Path, - LoadFileIcon = false, - FileExtension = itemFileExtension, - FileSizeBytes = (long)props.Size, - FileSize = itemSize, - ItemDateModifiedReal = props.DateModified, - ItemDateCreatedReal = file.DateCreated, - ItemType = itemType, - Opacity = 1, - ItemDateDeletedReal = binFile.DateDeleted, - ItemOriginalPath = binFile.OriginalPath - }; - } - else if (FileExtensionHelpers.IsShortcutOrUrlFile(file.Path)) - { - var isUrl = FileExtensionHelpers.IsWebLinkFile(file.Path); - var shortcutItem = new ShortcutItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - FileExtension = itemFileExtension, - IsHiddenItem = false, - Opacity = 1, - FileImage = null, - LoadFileIcon = false, - ItemNameRaw = file.Name, - ItemDateModifiedReal = props.DateModified, - ItemDateCreatedReal = file.DateCreated, - ItemType = isUrl ? Strings.ShortcutWebLinkFileType.GetLocalizedResource() : Strings.Shortcut.GetLocalizedResource(), - ItemPath = file.Path, - FileSize = itemSize, - FileSizeBytes = (long)props.Size, - IsUrl = isUrl, - }; - listedItem = shortcutItem; - } - else - { - listedItem = new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.File, - ItemNameRaw = file.Name, - ItemPath = file.Path, - LoadFileIcon = false, - FileExtension = itemFileExtension, - FileSizeBytes = (long)props.Size, - FileSize = itemSize, - ItemDateModifiedReal = props.DateModified, - ItemDateCreatedReal = file.DateCreated, - ItemType = itemType, - Opacity = 1 - }; - } - } - return listedItem - ?? throw new InvalidOperationException($"The search result '{item.Path}' is neither a file nor a folder."); - } - - private QueryOptions ToQueryOptions() - { - var query = new QueryOptions - { - FolderDepth = FolderDepth.Deep, - UserSearchFilter = AQSQuery ?? string.Empty, - }; - - query.IndexerOption = IndexerOption.UseIndexerWhenAvailable; - - query.SortOrder.Clear(); - query.SortOrder.Add(new SortEntry { PropertyName = "System.Search.Rank", AscendingOrder = false }); - - query.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, null); - - return query; - } - - private static Task> GetStorageFolderAsync(string path) - => FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path)); - - private static Task> GetStorageFileAsync(string path) - => FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFileFromPathAsync(path)); - } -} diff --git a/src/Files.App/Utils/Storage/Search/FolderSearch.cs b/src/Files.App/Utils/Storage/Search/FolderSearch.cs index c91b3b69837b..dba07423b060 100644 --- a/src/Files.App/Utils/Storage/Search/FolderSearch.cs +++ b/src/Files.App/Utils/Storage/Search/FolderSearch.cs @@ -12,18 +12,11 @@ namespace Files.App.Utils.Storage public sealed partial class FolderSearch { private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService(); -#if WINDOWS - private DrivesViewModel drivesViewModel = Ioc.Default.GetRequiredService(); - private readonly IStorageTrashBinService StorageTrashBinService = Ioc.Default.GetRequiredService(); -#endif private readonly IFileTagsSettingsService fileTagsSettingsService = Ioc.Default.GetRequiredService(); private readonly ILogger logger = Ioc.Default.GetRequiredService>(); private static readonly string folderTypeTextLocalized = Strings.Folder.GetLocalizedResource(); -#if WINDOWS - private const uint defaultStepSize = 500; -#endif public string? Query { get; set; } @@ -128,21 +121,7 @@ public async Task SearchAsync(IList results, CancellationToken token private async Task AddItemsForHomeAsync(IList results, CancellationToken token) { -#if !WINDOWS await SearchLinuxAsync("Home", results, token); -#else - if (IsTagQuery(AQSQuery)) - { - await SearchTagsAsync("", results, token); // Search tags everywhere, not only local drives - } - else - { - foreach (var drive in drivesViewModel.Drives.ToList().Cast().Where(x => !x.IsNetwork)) - { - await AddItemsAsync(drive.Path!, results, token); - } - } -#endif } public async Task> SearchAsync() diff --git a/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFile.cs b/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFile.cs index 3414df304251..ffb0383b29b3 100644 --- a/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFile.cs +++ b/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFile.cs @@ -41,11 +41,7 @@ public StorageProvider? Provider public abstract IStorageItemExtraProperties Properties { get; } [MaybeNull] StorageItemContentProperties IStorageItemProperties.Properties -#if WINDOWS - => this is SystemStorageFile file ? file.File.Properties : null; -#else => null; -#endif public static implicit operator BaseStorageFile?(StorageFile? value) { @@ -170,21 +166,12 @@ IAsyncOperation IStorageFile.CopyAsync(IStorageFolder destinationFo return Task.FromResult(null).AsAsyncOperation(); } -#if WINDOWS - public static IAsyncOperation GetFileFromPathAsync(string path) - { - return AsyncInfo.Run(async (cancellationToken) - => await ZipStorageFile.FromPathAsync(path) ?? await FtpStorageFile.FromPathAsync(path) ?? await ShellStorageFile.FromPathAsync(path) ?? await NativeStorageFile.FromPathAsync(path) ?? await SystemStorageFile.FromPathAsync(path) - ); - } -#else // LINUX-TODO(storage): remove legacy WinRT resolution after downstream consumers use IStorableResolver. public static IAsyncOperation GetFileFromPathAsync(string path) { return AsyncInfo.Run(async (cancellationToken) => await FtpStorageFile.FromPathAsync(path) ?? await SystemStorageFile.FromPathAsync(path)); } -#endif public async Task ReadTextAsync(int maxLength = -1) { diff --git a/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFolder.cs b/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFolder.cs index c25b7a8fa5a2..88d59c9666cd 100644 --- a/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFolder.cs +++ b/src/Files.App/Utils/Storage/StorageBaseItems/BaseStorageFolder.cs @@ -33,11 +33,7 @@ public StorageProvider? Provider [MaybeNull] StorageItemContentProperties IStorageItemProperties.Properties -#if WINDOWS - => this is SystemStorageFolder folder ? folder.Folder.Properties : null; -#else => null; -#endif public static implicit operator BaseStorageFolder?(StorageFolder? value) { @@ -144,21 +140,12 @@ IAsyncOperation IStorageFolder.GetFolderAsync(string name) }); } -#if WINDOWS - public static IAsyncOperation GetFolderFromPathAsync(string path) - { - return - AsyncInfo.Run(async (cancellationToken) - => await ZipStorageFolder.FromPathAsync(path) ?? await FtpStorageFolder.FromPathAsync(path) ?? await ShellStorageFolder.FromPathAsync(path) ?? await SystemStorageFolder.FromPathAsync(path)); - } -#else // LINUX-TODO(storage): remove legacy WinRT resolution after downstream consumers use IStorableResolver. public static IAsyncOperation GetFolderFromPathAsync(string path) { return AsyncInfo.Run(async (cancellationToken) => await FtpStorageFolder.FromPathAsync(path) ?? await SystemStorageFolder.FromPathAsync(path)); } -#endif public abstract IAsyncOperation?> GetFoldersAsync(); diff --git a/src/Files.App/Utils/Storage/StorageBaseItems/IPasswordProtectedItem.cs b/src/Files.App/Utils/Storage/StorageBaseItems/IPasswordProtectedItem.cs index 3702a4511380..eba020146cf1 100644 --- a/src/Files.App/Utils/Storage/StorageBaseItems/IPasswordProtectedItem.cs +++ b/src/Files.App/Utils/Storage/StorageBaseItems/IPasswordProtectedItem.cs @@ -5,9 +5,6 @@ using Files.Platform.Abstractions.Archives; using System; using System.Threading.Tasks; -#if WINDOWS -using SevenZip; -#endif namespace Files.App.Utils.Storage { @@ -20,10 +17,6 @@ public interface IPasswordProtectedItem async Task RetryWithCredentialsAsync(Func> func, Exception exception) { var handled = -#if WINDOWS - exception is SevenZipOpenFailedException szofex && szofex.Result is OperationResult.WrongPassword || - exception is ExtractionFailedException efex && efex.Result is OperationResult.WrongPassword || -#endif exception is ArchivePasswordException || exception is FtpAuthenticationException || exception is ICSharpCode.SharpZipLib.Zip.ZipException szlzex && szlzex.Message.Contains("password"); @@ -39,10 +32,6 @@ exception is FtpAuthenticationException || async Task RetryWithCredentialsAsync(Func func, Exception exception) { var handled = -#if WINDOWS - exception is SevenZipOpenFailedException szofex && szofex.Result is OperationResult.WrongPassword || - exception is ExtractionFailedException efex && efex.Result is OperationResult.WrongPassword || -#endif exception is ArchivePasswordException || exception is FtpAuthenticationException || exception is ICSharpCode.SharpZipLib.Zip.ZipException szlzex && szlzex.Message.Contains("password"); diff --git a/src/Files.App/Utils/Storage/StorageItems/FtpStorageFile.cs b/src/Files.App/Utils/Storage/StorageItems/FtpStorageFile.cs index 64aab4378f2f..33f97d11e326 100644 --- a/src/Files.App/Utils/Storage/StorageItems/FtpStorageFile.cs +++ b/src/Files.App/Utils/Storage/StorageItems/FtpStorageFile.cs @@ -131,12 +131,8 @@ public override IAsyncOperation GetBasicPropertiesAsync() var inStream = await ftpClient.OpenRead(FtpPath, token: cancellationToken); var nsStream = new NonSeekableRandomAccessStreamForRead(inStream, (ulong)inStream.Length) { DisposeCallback = ftpClient.Dispose }; -#if WINDOWS - return new StreamWithContentType(nsStream); -#else // LINUX-TODO(storage): use the archive/FTP storable stream instead of the WinRT content stream. throw new NotSupportedException("WinRT content streams are Windows-only."); -#endif }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); } public override IAsyncOperation OpenSequentialReadAsync() diff --git a/src/Files.App/Utils/Storage/StorageItems/NativeStorageFile.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/NativeStorageFile.Windows.cs deleted file mode 100644 index 7d772e5ceb48..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/NativeStorageFile.Windows.cs +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using System.IO; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Streams; -using Windows.Win32; -using IO = System.IO; - -namespace Files.App.Utils.Storage -{ - /// - /// Shortcuts and alternate data stream. - /// Uses *FromApp methods for file operations - /// - public sealed partial class NativeStorageFile : BaseStorageFile - { - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string ContentType => "application/octet-stream"; - public override string FileType => IO.Path.GetExtension(Name); - public override string FolderRelativeId => $"0\\{Name}"; - - public bool IsShortcut => FileExtensionHelpers.IsShortcutOrUrlFile(FileType); - public bool IsAlternateStream => System.Text.RegularExpressions.Regex.IsMatch(Path, @"\w:\w"); - - private string? _DisplayType; - public override string DisplayType - { - get - { - if (_DisplayType is not null) - return _DisplayType; - - // Try to get the proper display type from Windows Shell - _DisplayType = GetDisplayTypeFromShell(); - - return _DisplayType; - } - } - - private string GetDisplayTypeFromShell() - { - var extension = IO.Path.GetExtension(Name); - - var typeName = FileTypesHelper.GetLocalizedTypeName(extension); - if (!string.IsNullOrEmpty(typeName)) - return typeName; - - // Fallback to generic format - var itemType = Strings.File.GetLocalizedResource(); - if (Name.Contains('.', StringComparison.Ordinal)) - itemType = extension?.Trim('.') + " " + itemType; - - return itemType; - } - - public override DateTimeOffset DateCreated { get; } - public override Windows.Storage.FileAttributes Attributes { get; } = Windows.Storage.FileAttributes.Normal; - public override IStorageItemExtraProperties Properties => new BaseBasicStorageItemExtraProperties(this); - - public NativeStorageFile(string path, string name, DateTimeOffset dateCreated) - { - Path = path; - Name = name; - DateCreated = dateCreated; - } - - public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) - => throw new NotSupportedException(); - - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder) - => CopyAsync(destinationFolder, Name, NameCollisionOption.FailIfExists); - - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName) - => CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists); - - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (string.IsNullOrEmpty(destinationFolder.Path)) - { - throw new NotSupportedException(); - } - var destination = IO.Path.Combine(destinationFolder.Path, desiredNewName); - var destFile = new NativeStorageFile(destination, desiredNewName, DateTime.Now); - if (!IsAlternateStream) - { - if (!await Task.Run(() => PInvoke.CopyFileFromApp(Path, destination, option != NameCollisionOption.ReplaceExisting))) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - } - else - { - destFile.CreateFile(); - await using (var inStream = await this.OpenStreamForReadAsync()) - await using (var outStream = await destFile.OpenStreamForWriteAsync()) - { - await inStream.CopyToAsync(outStream, cancellationToken); - await outStream.FlushAsync(cancellationToken); - } - } - return destFile; - }); - } - - private void CreateFile() - { - using var hFile = Win32Helper.CreateFileForWrite(Path, false); - if (hFile.IsInvalid) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - } - - public override IAsyncAction DeleteAsync() - { - return AsyncInfo.Run(_ => - { - if (!PInvoke.DeleteFileFromApp(Path)) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - - return Task.CompletedTask; - }); - } - - public override IAsyncAction DeleteAsync(StorageDeleteOption option) - { - if (option == StorageDeleteOption.PermanentDelete) - { - return DeleteAsync(); - } - throw new NotSupportedException(); - } - - public override IAsyncOperation GetBasicPropertiesAsync() - { - return Task.FromResult(new BaseBasicProperties()).AsAsyncOperation(); - } - - public override IAsyncOperation GetParentAsync() - => throw new NotSupportedException(); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - => throw new NotSupportedException(); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - => throw new NotSupportedException(); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - => throw new NotSupportedException(); - - public static IAsyncOperation FromPathAsync(string path) - { - if (IsNativePath(path) && CheckAccess(path)) - { - var name = IO.Path.GetFileName(path); - return Task.FromResult(new NativeStorageFile(path, name[(name.LastIndexOf(':') + 1)..], DateTime.Now)).AsAsyncOperation(); - } - return Task.FromResult(null).AsAsyncOperation(); - } - - private static bool CheckAccess(string path) - { - using var hFile = Win32Helper.OpenFileForRead(path); - return !hFile.IsInvalid; - } - - private static bool IsNativePath(string path) - { - var isShortcut = FileExtensionHelpers.IsShortcutOrUrlFile(path); - var isAlternateStream = RegexHelpers.AlternateStream().IsMatch(path); - var hasRestrictedAttributes = HasHiddenOrSystemAttributes(path); - return isShortcut || isAlternateStream || hasRestrictedAttributes; - } - - private static bool HasHiddenOrSystemAttributes(string path) - { - try - { - // Check if file has hidden or system attributes - // This will work even if WinRT APIs fail - var fileInfo = new FileInfo(path); - if (!fileInfo.Exists) - return false; - - return (fileInfo.Attributes & (IO.FileAttributes.Hidden | IO.FileAttributes.System)) != 0; - } - catch - { - return false; - } - } - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - public override bool IsOfType(StorageItemTypes type) => type is StorageItemTypes.File; - - public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) - => throw new NotSupportedException(); - - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder) - => MoveAsync(destinationFolder, Name, NameCollisionOption.FailIfExists); - - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) - => MoveAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists); - - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (string.IsNullOrEmpty(destinationFolder.Path)) - { - throw new NotSupportedException(); - } - var destination = IO.Path.Combine(destinationFolder.Path, desiredNewName); - if (!IsAlternateStream) - { - if (!await Task.Run(() => PInvoke.MoveFileFromApp(Path, destination))) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - } - else - { - await CopyAsync(destinationFolder, desiredNewName, option); - await DeleteAsync(); - } - }); - } - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode) - { - var hFile = Win32Helper.OpenFileForRead(Path, accessMode == FileAccessMode.ReadWrite); - return Task.FromResult(new FileStream(hFile, accessMode == FileAccessMode.ReadWrite ? FileAccess.ReadWrite : FileAccess.Read).AsRandomAccessStream()).AsAsyncOperation(); - } - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) => OpenAsync(accessMode); - - public override IAsyncOperation OpenReadAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - var stream = await OpenAsync(FileAccessMode.Read) - ?? throw new IOException("The native file could not be opened for reading."); - return new StreamWithContentType(stream); - }); - } - - public override IAsyncOperation OpenSequentialReadAsync() - { - var hFile = Win32Helper.OpenFileForRead(Path); - return Task.FromResult(new FileStream(hFile, FileAccess.Read).AsInputStream()).AsAsyncOperation(); - } - - public override IAsyncOperation OpenTransactedWriteAsync() - => throw new NotSupportedException(); - - public override IAsyncOperation OpenTransactedWriteAsync(StorageOpenOptions options) - => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) - => RenameAsync(desiredName, NameCollisionOption.FailIfExists); - - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - { - return AsyncInfo.Run(async (cancellationToken) => - { - var parentPath = IO.Path.GetDirectoryName(Path) ?? throw new InvalidOperationException("The file path has no parent."); - string destination = IO.Path.Combine(parentPath, desiredName); - var destFile = new NativeStorageFile(destination, desiredName, DateTime.Now); - if (!IsAlternateStream) - { - if (!await Task.Run(() => PInvoke.MoveFileFromApp(Path, destination))) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - } - else - { - destFile.CreateFile(); - await using (var inStream = await this.OpenStreamForReadAsync()) - await using (var outStream = await destFile.OpenStreamForWriteAsync()) - { - await inStream.CopyToAsync(outStream, cancellationToken); - await outStream.FlushAsync(cancellationToken); - } - await DeleteAsync(); - } - }); - } - - public override IAsyncOperation ToStorageFileAsync() - => throw new NotSupportedException(); - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/ShellStorageFile.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/ShellStorageFile.Windows.cs deleted file mode 100644 index 4727af593fb0..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/ShellStorageFile.Windows.cs +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Streams; -using Windows.Win32.UI.WindowsAndMessaging; -using IO = System.IO; - -namespace Files.App.Utils.Storage -{ - public sealed partial class ShortcutStorageFile : ShellStorageFile, IShortcutStorageItem - { - public string? TargetPath { get; } - public string? Arguments { get; } - public string? WorkingDirectory { get; } - public bool RunAsAdmin { get; } - public SHOW_WINDOW_CMD ShowWindowCommand { get; set; } - - public ShortcutStorageFile(ShellLinkItem item) : base(item) - { - TargetPath = item.TargetPath; - Arguments = item.Arguments; - WorkingDirectory = item.WorkingDirectory; - RunAsAdmin = item.RunAsAdmin; - ShowWindowCommand = (Windows.Win32.UI.WindowsAndMessaging.SHOW_WINDOW_CMD)item.ShowWindowCommand; - } - } - - public sealed partial class BinStorageFile : ShellStorageFile, IBinStorageItem - { - public string? OriginalPath { get; } - public DateTimeOffset DateDeleted { get; } - - public BinStorageFile(ShellFileItem item) : base(item) - { - OriginalPath = item.FilePath; - DateDeleted = item.RecycleDate; - } - } - - public partial class ShellStorageFile : BaseStorageFile - { - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string ContentType => "application/octet-stream"; - public override string FileType => IO.Path.GetExtension(Name); - public override string FolderRelativeId => $"0\\{Name}"; - - public override string DisplayType { get; } - - public override DateTimeOffset DateCreated { get; } - - public override FileAttributes Attributes => FileAttributes.Normal | FileAttributes.ReadOnly; - - private IStorageItemExtraProperties? properties; - public override IStorageItemExtraProperties Properties => properties ??= new BaseBasicStorageItemExtraProperties(this); - - public ShellStorageFile(ShellFileItem item) - { - Name = item.FileName - ?? throw new IO.InvalidDataException("The shell item does not have a file name."); - Path = item.RecyclePath // True path on disk - ?? throw new IO.InvalidDataException("The shell item does not have a path."); - DateCreated = item.CreatedDate; - DisplayType = item.FileType ?? string.Empty; - } - - public override IAsyncOperation ToStorageFileAsync() => throw new NotSupportedException(); - - public static ShellStorageFile FromShellItem(ShellFileItem item) - { - if (item.RecyclePath?.Contains("$Recycle.Bin", StringComparison.OrdinalIgnoreCase) is true) - return new BinStorageFile(item); - - if (item is ShellLinkItem linkItem) - return new ShortcutStorageFile(linkItem); - - return new ShellStorageFile(item); - } - - public static IAsyncOperation FromPathAsync(string path) - { - if (ShellStorageFolder.IsShellPath(path) && GetFile(path) is ShellFileItem file) - return Task.FromResult(FromShellItem(file)).AsAsyncOperation(); - return Task.FromResult(null).AsAsyncOperation(); - } - - private static ShellFileItem? GetFile(string path) - { - try - { - using var shellItem = ShellFolderExtensions.GetShellItemFromPathOrPIDL(path); - return ShellFolderExtensions.GetShellFileItem(shellItem); - } - catch - { - // Can happen when dealing with recent items or when browsing shell:::{679f85cb-0220-4080-b29b-5540cc05aab6} - return default; - } - } - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - public override bool IsOfType(StorageItemTypes type) => type is StorageItemTypes.File; - - public override IAsyncOperation GetParentAsync() => throw new NotSupportedException(); - public override IAsyncOperation GetBasicPropertiesAsync() => GetBasicProperties().AsAsyncOperation(); - - public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) => throw new NotSupportedException(); - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder) => throw new NotSupportedException(); - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName) => throw new NotSupportedException(); - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncAction DeleteAsync() => throw new NotSupportedException(); - public override IAsyncAction DeleteAsync(StorageDeleteOption option) => throw new NotSupportedException(); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (ShellStorageFolder.IsShellPath(Path)) - { - return null; - } - var zipFile = await StorageFile.GetFileFromPathAsync(Path); - return await zipFile.GetThumbnailAsync(mode); - }); - } - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (ShellStorageFolder.IsShellPath(Path)) - { - return null; - } - var zipFile = await StorageFile.GetFileFromPathAsync(Path); - return await zipFile.GetThumbnailAsync(mode, requestedSize); - }); - } - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (ShellStorageFolder.IsShellPath(Path)) - { - return null; - } - var zipFile = await StorageFile.GetFileFromPathAsync(Path); - return await zipFile.GetThumbnailAsync(mode, requestedSize, options); - }); - } - - public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder) => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode) => throw new NotSupportedException(); - public override IAsyncOperation OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) => throw new NotSupportedException(); - public override IAsyncOperation OpenReadAsync() => throw new NotSupportedException(); - public override IAsyncOperation OpenSequentialReadAsync() => throw new NotSupportedException(); - - public override IAsyncOperation OpenTransactedWriteAsync() => throw new NotSupportedException(); - public override IAsyncOperation OpenTransactedWriteAsync(StorageOpenOptions options) => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) => throw new NotSupportedException(); - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) => throw new NotSupportedException(); - - private Task GetBasicProperties() - { - if (GetFile(Path) is ShellFileItem file) - { - return Task.FromResult(new ShellFileBasicProperties(file)); - } - return Task.FromResult(new BaseBasicProperties()); - } - - private sealed partial class ShellFileBasicProperties : BaseBasicProperties - { - private readonly ShellFileItem file; - - public ShellFileBasicProperties(ShellFileItem folder) => file = folder; - - public override ulong Size => file.FileSizeBytes; - - public override DateTimeOffset DateCreated => file.CreatedDate; - public override DateTimeOffset DateModified => file.ModifiedDate; - } - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/ShellStorageFolder.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/ShellStorageFolder.Windows.cs deleted file mode 100644 index e5fd5aec6e92..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/ShellStorageFolder.Windows.cs +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Search; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Utils.Storage -{ - public sealed partial class ShortcutStorageFolder : ShellStorageFolder, IShortcutStorageItem - { - public string? TargetPath { get; } - public string? Arguments { get; } - public string? WorkingDirectory { get; } - public bool RunAsAdmin { get; } - public SHOW_WINDOW_CMD ShowWindowCommand { get; set; } - - public ShortcutStorageFolder(ShellLinkItem item) : base(item) - { - TargetPath = item.TargetPath; - Arguments = item.Arguments; - WorkingDirectory = item.WorkingDirectory; - RunAsAdmin = item.RunAsAdmin; - ShowWindowCommand = (Windows.Win32.UI.WindowsAndMessaging.SHOW_WINDOW_CMD)item.ShowWindowCommand; - } - } - - public interface IShortcutStorageItem : IStorageItem - { - string? TargetPath { get; } - string? Arguments { get; } - string? WorkingDirectory { get; } - bool RunAsAdmin { get; } - } - - public sealed partial class BinStorageFolder : ShellStorageFolder, IBinStorageItem - { - public string? OriginalPath { get; } - public DateTimeOffset DateDeleted { get; } - - public BinStorageFolder(ShellFileItem item) : base(item) - { - OriginalPath = item.FilePath; - DateDeleted = item.RecycleDate; - } - } - - public interface IBinStorageItem : IStorageItem - { - string? OriginalPath { get; } - DateTimeOffset DateDeleted { get; } - } - - public partial class ShellStorageFolder : BaseStorageFolder - { - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string DisplayType { get; } - public override string FolderRelativeId => $"0\\{Name}"; - - public override DateTimeOffset DateCreated { get; } - public override Windows.Storage.FileAttributes Attributes => Windows.Storage.FileAttributes.Directory; - public override IStorageItemExtraProperties Properties => new BaseBasicStorageItemExtraProperties(this); - - public ShellStorageFolder(ShellFileItem item) - { - Name = item.FileName - ?? throw new System.IO.InvalidDataException("The shell item does not have a file name."); - Path = item.RecyclePath // True path on disk - ?? throw new System.IO.InvalidDataException("The shell item does not have a path."); - DateCreated = item.CreatedDate; - DisplayType = item.FileType ?? string.Empty; - } - - public static bool IsShellPath(string? path) - { - return path is not null && - (path.StartsWith("shell:", StringComparison.OrdinalIgnoreCase) || - path.StartsWith("::{", StringComparison.Ordinal) || - path.StartsWith(@"\\SHELL\", StringComparison.Ordinal)); - } - - public static ShellStorageFolder FromShellItem(ShellFileItem item) - { - if (item is ShellLinkItem linkItem) - return new ShortcutStorageFolder(linkItem); - - if (item.RecyclePath?.Contains("$Recycle.Bin", StringComparison.OrdinalIgnoreCase) is true) - return new BinStorageFolder(item); - - return new ShellStorageFolder(item); - } - - public static IAsyncOperation FromPathAsync(string path) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (IsShellPath(path)) - { - var res = await GetFolderAndItems(path, false); - if (res.Folder is not null) - { - return FromShellItem(res.Folder); - } - } - return null; - }); - } - - protected static async Task<(ShellFileItem? Folder, List? Items)> GetFolderAndItems(string path, bool enumerate, int startIndex = 0, int maxItemsToRetrieve = int.MaxValue) - { - return await Win32Helper.GetShellFolderAsync(path, !enumerate, enumerate, startIndex, maxItemsToRetrieve); - } - - public override IAsyncOperation ToStorageFolderAsync() => throw new NotSupportedException(); - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - public override bool IsOfType(StorageItemTypes type) => type == StorageItemTypes.Folder; - - public override IAsyncOperation GetIndexedStateAsync() => Task.FromResult(IndexedState.NotIndexed).AsAsyncOperation(); - - public override IAsyncOperation GetParentAsync() => throw new NotSupportedException(); - - public override IAsyncOperation GetBasicPropertiesAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - var res = await GetFolderAndItems(Path, false); - return res.Folder is not null ? new ShellFolderBasicProperties(res.Folder) : new BaseBasicProperties(); - }); - } - - public override IAsyncOperation GetItemAsync(string name) - { - return AsyncInfo.Run(async (cancellationToken) => - { - var res = await GetFolderAndItems(Path, true); - if (res.Items is null) - { - return null; - } - - var entry = res.Items.FirstOrDefault(x => x.FileName is not null && x.FileName.Equals(name, StringComparison.OrdinalIgnoreCase)); - if (entry is null) - { - return null; - } - - if (entry.IsFolder) - { - return ShellStorageFolder.FromShellItem(entry); - } - - return ShellStorageFile.FromShellItem(entry); - }); - } - public override IAsyncOperation TryGetItemAsync(string name) - { - return AsyncInfo.Run(async (cancellationToken) => - { - try - { - return await GetItemAsync(name); - } - catch - { - return null; - } - }); - } - public override IAsyncOperation?> GetItemsAsync() - => AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetItemsAsync(0, int.MaxValue) - ?? throw new InvalidOperationException("The shell folder could not be enumerated."); - return items.ToList(); - }); - public override IAsyncOperation?> GetItemsAsync(uint startIndex, uint maxItemsToRetrieve) - { - return AsyncInfo.Run?>(async (cancellationToken) => - { - var res = await GetFolderAndItems(Path, true, (int)startIndex, (int)maxItemsToRetrieve); - if (res.Items is null) - { - return null; - } - - var items = new List(); - foreach (var entry in res.Items) - { - if (entry.IsFolder) - { - items.Add(ShellStorageFolder.FromShellItem(entry)); - } - else - { - items.Add(ShellStorageFile.FromShellItem(entry)); - } - } - return items; - }); - } - - public override IAsyncOperation GetFileAsync(string name) - => AsyncInfo.Run(async (cancellationToken) => await GetItemAsync(name) as ShellStorageFile); - public override IAsyncOperation?> GetFilesAsync() - => AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetItemsAsync(); - return items?.OfType().ToList(); - }); - public override IAsyncOperation?> GetFilesAsync(CommonFileQuery query) - => AsyncInfo.Run?>(async (cancellationToken) => await GetFilesAsync()); - public override IAsyncOperation?> GetFilesAsync(CommonFileQuery query, uint startIndex, uint maxItemsToRetrieve) - => AsyncInfo.Run?>(async (cancellationToken) => - { - var files = await GetFilesAsync() - ?? throw new InvalidOperationException("The shell folder files could not be enumerated."); - return files.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList(); - }); - - public override IAsyncOperation GetFolderAsync(string name) - => AsyncInfo.Run(async (cancellationToken) => await GetItemAsync(name) as ShellStorageFolder); - public override IAsyncOperation?> GetFoldersAsync() - => AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetItemsAsync(); - return items?.OfType().ToList(); - }); - public override IAsyncOperation?> GetFoldersAsync(CommonFolderQuery query) - => AsyncInfo.Run?>(async (cancellationToken) => await GetFoldersAsync()); - public override IAsyncOperation?> GetFoldersAsync(CommonFolderQuery query, uint startIndex, uint maxItemsToRetrieve) - { - return AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetFoldersAsync() - ?? throw new InvalidOperationException("The shell folder children could not be enumerated."); - return items.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList(); - }); - } - - public override IAsyncOperation CreateFileAsync(string desiredName) => throw new NotSupportedException(); - public override IAsyncOperation CreateFileAsync(string desiredName, CreationCollisionOption options) - => throw new NotSupportedException(); - - public override IAsyncOperation CreateFolderAsync(string desiredName) => throw new NotSupportedException(); - public override IAsyncOperation CreateFolderAsync(string desiredName, CreationCollisionOption options) - => throw new NotSupportedException(); - - public override IAsyncOperation MoveAsync(IStorageFolder destinationFolder) => throw new NotSupportedException(); - public override IAsyncOperation MoveAsync(IStorageFolder destinationFolder, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) => throw new NotSupportedException(); - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncAction DeleteAsync() => throw new NotSupportedException(); - public override IAsyncAction DeleteAsync(StorageDeleteOption option) => throw new NotSupportedException(); - - public override bool AreQueryOptionsSupported(QueryOptions queryOptions) => false; - public override bool IsCommonFileQuerySupported(CommonFileQuery query) => false; - public override bool IsCommonFolderQuerySupported(CommonFolderQuery query) => false; - - public override StorageItemQueryResult CreateItemQuery() => throw new NotSupportedException(); - public override BaseStorageItemQueryResult CreateItemQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override StorageFileQueryResult CreateFileQuery() => throw new NotSupportedException(); - public override StorageFileQueryResult CreateFileQuery(CommonFileQuery query) => throw new NotSupportedException(); - public override BaseStorageFileQueryResult CreateFileQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override StorageFolderQueryResult CreateFolderQuery() => throw new NotSupportedException(); - public override StorageFolderQueryResult CreateFolderQuery(CommonFolderQuery query) => throw new NotSupportedException(); - public override BaseStorageFolderQueryResult CreateFolderQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (IsShellPath(Path)) - { - return null; - } - var zipFolder = await StorageFolder.GetFolderFromPathAsync(Path); - return await zipFolder.GetThumbnailAsync(mode); - }); - } - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (IsShellPath(Path)) - { - return null; - } - var zipFolder = await StorageFolder.GetFolderFromPathAsync(Path); - return await zipFolder.GetThumbnailAsync(mode, requestedSize); - }); - } - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (IsShellPath(Path)) - { - return null; - } - var zipFolder = await StorageFolder.GetFolderFromPathAsync(Path); - return await zipFolder.GetThumbnailAsync(mode, requestedSize, options); - }); - } - - private sealed partial class ShellFolderBasicProperties : BaseBasicProperties - { - private readonly ShellFileItem folder; - - public ShellFolderBasicProperties(ShellFileItem folder) => this.folder = folder; - - public override ulong Size => folder.FileSizeBytes; - - public override DateTimeOffset DateCreated => folder.CreatedDate; - public override DateTimeOffset DateModified => folder.ModifiedDate; - } - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/StreamWithContentType.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/StreamWithContentType.Windows.cs deleted file mode 100644 index 23c8afe68211..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/StreamWithContentType.Windows.cs +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using System.Runtime.InteropServices.Marshalling; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage.Streams; -using Windows.Win32; -using Windows.Win32.System.Com; - -namespace Files.App.Utils.Storage -{ - public sealed partial class StreamWithContentType : IRandomAccessStreamWithContentType - { - private IRandomAccessStream baseStream; - - public StreamWithContentType(IRandomAccessStream stream) - { - baseStream = stream; - } - - public IInputStream GetInputStreamAt(ulong position) => baseStream.GetInputStreamAt(position); - - public IOutputStream GetOutputStreamAt(ulong position) => baseStream.GetOutputStreamAt(position); - - public void Seek(ulong position) => baseStream.Seek(position); - - public IRandomAccessStream CloneStream() => baseStream.CloneStream(); - - public bool CanRead => baseStream.CanRead; - - public bool CanWrite => baseStream.CanWrite; - - public ulong Position => baseStream.Position; - - public ulong Size { get => baseStream.Size; set => baseStream.Size = value; } - - public IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) - { - return baseStream.ReadAsync(buffer, count, options); - } - - public IAsyncOperationWithProgress WriteAsync(IBuffer buffer) => baseStream.WriteAsync(buffer); - - public IAsyncOperation FlushAsync() => baseStream.FlushAsync(); - - public void Dispose() - { - baseStream.Dispose(); - } - - public string ContentType { get; set; } = "application/octet-stream"; - } - - public sealed partial class ComStreamWrapper : Stream - { - private IStream? iStream; - private STATSTG iStreamStat; - private STGMEDIUM medium; - - public ComStreamWrapper(IStream stream, STGMEDIUM medium) - { - iStream = stream; - this.medium = medium; - try - { - iStream.Stat(out iStreamStat, STATFLAG.STATFLAG_NONAME).ThrowOnFailure(); - } - catch - { - ReleaseResources(); - throw; - } - } - - public override bool CanRead => true; - - public override bool CanSeek => true; - - public override bool CanWrite => false; - - public override long Length => checked((long)iStreamStat.cbSize); - - public override long Position - { - get => Seek(0, SeekOrigin.Current); - set => Seek(value, SeekOrigin.Begin); - } - - public override void Flush() - { - } - - public override int Read(byte[] buffer, int offset, int count) - { - ObjectDisposedException.ThrowIf(iStream is null, this); - iStream.Read(buffer.AsSpan(offset, count), out uint bytesRead).ThrowOnFailure(); - return checked((int)bytesRead); - } - - public override long Seek(long offset, SeekOrigin origin) - { - ObjectDisposedException.ThrowIf(iStream is null, this); - iStream.Seek(offset, origin, out ulong newPosition).ThrowOnFailure(); - return checked((long)newPosition); - } - - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException(); - } - - protected override void Dispose(bool disposing) - { - if (iStream is null) - return; - - base.Dispose(disposing); - ReleaseResources(); - } - - private void ReleaseResources() - { - IStream? stream = iStream; - iStream = null; - try - { - if ((object?)stream is ComObject comObject) - comObject.FinalRelease(); - } - finally - { - PInvoke.ReleaseStgMedium(ref medium); - medium = default; - } - } - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/SystemStorageFile.cs b/src/Files.App/Utils/Storage/StorageItems/SystemStorageFile.cs index 017bf61e7780..c409fd786a77 100644 --- a/src/Files.App/Utils/Storage/StorageItems/SystemStorageFile.cs +++ b/src/Files.App/Utils/Storage/StorageItems/SystemStorageFile.cs @@ -21,30 +21,14 @@ public sealed partial class SystemStorageFile : BaseStorageFile public override string Name => File.Name; public override string DisplayName => File.DisplayName; public override string ContentType => File.ContentType; -#if WINDOWS - public override string DisplayType => File.DisplayType; -#else // Uno does not implement these members and throws public override string DisplayType => string.Empty; -#endif public override string FileType => File.FileType; -#if WINDOWS - public override string FolderRelativeId => File.FolderRelativeId; -#else public override string FolderRelativeId => string.Empty; -#endif public override DateTimeOffset DateCreated => File.DateCreated; -#if WINDOWS - public override Windows.Storage.FileAttributes Attributes => File.Attributes; -#else public override Windows.Storage.FileAttributes Attributes => default; -#endif -#if WINDOWS - public override IStorageItemExtraProperties Properties => File.Properties; -#else public override IStorageItemExtraProperties Properties => null!; -#endif public SystemStorageFile(StorageFile file) { @@ -125,33 +109,10 @@ public override IAsyncOperation GetBasicPropertiesAsync() return destFile; } } -#if WINDOWS - catch (UnauthorizedAccessException) // shortcuts & .url - { - if (!string.IsNullOrEmpty(destFolder.Path)) - { - var destination = IO.Path.Combine(destFolder.Path, desiredNewName); - var hFile = Win32Helper.CreateFileForWrite(destination, - option == NameCollisionOption.ReplaceExisting); - if (!hFile.IsInvalid) - { - await using (var inStream = await this.OpenStreamForReadAsync()) - await using (var outStream = new FileStream(hFile, FileAccess.Write)) - { - await inStream.CopyToAsync(outStream, cancellationToken); - await outStream.FlushAsync(cancellationToken); - } - return new NativeStorageFile(destination, desiredNewName, DateTime.Now); - } - } - throw; - } -#else catch (UnauthorizedAccessException) { throw; } -#endif }); } diff --git a/src/Files.App/Utils/Storage/StorageItems/SystemStorageFolder.cs b/src/Files.App/Utils/Storage/StorageItems/SystemStorageFolder.cs index 3c4e5b3e130f..41200a1b4e2d 100644 --- a/src/Files.App/Utils/Storage/StorageItems/SystemStorageFolder.cs +++ b/src/Files.App/Utils/Storage/StorageItems/SystemStorageFolder.cs @@ -19,29 +19,13 @@ public sealed partial class SystemStorageFolder : BaseStorageFolder public override string Path => Folder.Path; public override string Name => Folder.Name; public override string DisplayName => Folder.DisplayName; -#if WINDOWS - public override string DisplayType => Folder.DisplayType; -#else // Uno does not implement these members and throws public override string DisplayType => string.Empty; -#endif -#if WINDOWS - public override string FolderRelativeId => Folder.FolderRelativeId; -#else public override string FolderRelativeId => string.Empty; -#endif public override DateTimeOffset DateCreated => Folder.DateCreated; - #if WINDOWS - public override FileAttributes Attributes => Folder.Attributes; -#else public override FileAttributes Attributes => default; -#endif -#if WINDOWS - public override IStorageItemExtraProperties Properties => Folder.Properties; -#else public override IStorageItemExtraProperties Properties => null!; -#endif public SystemStorageFolder(StorageFolder folder) { @@ -51,30 +35,6 @@ public SystemStorageFolder(StorageFolder folder) public static IAsyncOperation FromPathAsync(string path) { -#if WINDOWS - if (path.EndsWith(ShellLibraryItem.EXTENSION)) - { - try - { - using var libraryFile = ShellItem.Open(path); - using var shellItem = new ShellLibraryEx(libraryFile.IShellItem, true); - if (shellItem is ShellLibraryEx library) - { - var libraryItem = ShellFolderExtensions.GetShellLibraryItem(library, path); - var firstFolder = libraryItem?.Folders?.FirstOrDefault(); - - if (firstFolder != null) - { - return AsyncInfo.Run(async (cancellationToken) => new SystemStorageFolder(await StorageFolder.GetFolderFromPathAsync(firstFolder))); - } - } - } - catch (Exception e) - { - App.Logger.LogWarning(e, null); - } - } -#endif return AsyncInfo.Run(async (cancellationToken) => new SystemStorageFolder(await StorageFolder.GetFolderFromPathAsync(path))); } diff --git a/src/Files.App/Utils/Storage/StorageItems/VirtualStorageFile.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/VirtualStorageFile.Windows.cs deleted file mode 100644 index dfec81bfb194..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/VirtualStorageFile.Windows.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Streams; -using IO = System.IO; - -namespace Files.App.Utils.Storage -{ - public sealed partial class VirtualStorageFile : BaseStorageFile - { - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string ContentType => "application/octet-stream"; - public override string FileType => IO.Path.GetExtension(Name); - public override string FolderRelativeId => $"0\\{Name}"; - - public override string DisplayType - { - get - { - var itemType = Strings.File.GetLocalizedResource(); - if (Name.Contains('.', StringComparison.Ordinal)) - { - itemType = IO.Path.GetExtension(Name).Trim('.') + " " + itemType; - } - return itemType; - } - } - - private Stream Contents { get; init; } - - public override DateTimeOffset DateCreated { get; } - public override Windows.Storage.FileAttributes Attributes { get; } = Windows.Storage.FileAttributes.Normal; - public override IStorageItemExtraProperties Properties => new BaseBasicStorageItemExtraProperties(this); - - public VirtualStorageFile(Stream contents, string cFileName) - { - Contents = contents; - Name = cFileName; - Path = ""; - } - - private async void StreamedFileWriterAsync(StreamedFileDataRequest request) - { - try - { - await using (var stream = request.AsStreamForWrite()) - { - await Contents.CopyToAsync(stream); - await stream.FlushAsync(); - } - request.Dispose(); - } - catch (Exception) - { - request.FailAndClose(StreamedFileFailureMode.Incomplete); - } - } - - public override IAsyncOperation GetBasicPropertiesAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - return new BaseBasicProperties(); - }); - } - - public override bool IsOfType(StorageItemTypes type) - { - return Attributes.HasFlag(Windows.Storage.FileAttributes.Directory) ? type == StorageItemTypes.Folder : type == StorageItemTypes.File; - } - - public override IAsyncOperation ToStorageFileAsync() - { - return StorageFile.CreateStreamedFileAsync(Name, StreamedFileWriterAsync, null); - } - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - - public override IAsyncOperation GetParentAsync() => throw new NotSupportedException(); - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode) - { - return Task.FromResult(Contents.AsRandomAccessStream()).AsAsyncOperation(); - } - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) => OpenAsync(accessMode); - - public override IAsyncOperation OpenReadAsync() - { - return Task.FromResult(new StreamWithContentType(Contents.AsRandomAccessStream())) - .AsAsyncOperation(); - } - - public override IAsyncOperation OpenSequentialReadAsync() - { - return Task.FromResult(Contents.AsInputStream()).AsAsyncOperation(); - } - - public override IAsyncOperation OpenTransactedWriteAsync() => throw new NotSupportedException(); - public override IAsyncOperation OpenTransactedWriteAsync(StorageOpenOptions options) => throw new NotSupportedException(); - - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder) - => CopyAsync(destinationFolder, Name, NameCollisionOption.FailIfExists); - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName) - => CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists); - - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - return AsyncInfo.Run(async (cancellationToken) => - { - var destFolder = destinationFolder.AsBaseStorageFolder() - ?? throw new NotSupportedException("The destination folder type is not supported."); - - if (destFolder is ICreateFileWithStream cwsf) - { - await using var inStream = await this.OpenStreamForReadAsync(); - return await cwsf.CreateFileAsync(inStream, desiredNewName, option.Convert()); - } - else - { - var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert()) - ?? throw new IOException($"Failed to create destination file '{desiredNewName}'."); - - await using (var inStream = await this.OpenStreamForReadAsync()) - await using (var outStream = await destFile.OpenStreamForWriteAsync()) - { - await inStream.CopyToAsync(outStream, cancellationToken); - await outStream.FlushAsync(cancellationToken); - } - return destFile; - } - }); - } - - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder) => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) => throw new NotSupportedException(); - public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) - => RenameAsync(desiredName, NameCollisionOption.FailIfExists); - - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - => throw new NotSupportedException(); - - public override IAsyncAction DeleteAsync() => throw new NotSupportedException(); - - public override IAsyncAction DeleteAsync(StorageDeleteOption option) => throw new NotSupportedException(); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - => Task.FromResult(null).AsAsyncOperation(); - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - => Task.FromResult(null).AsAsyncOperation(); - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - => Task.FromResult(null).AsAsyncOperation(); - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/VirtualStorageFolder.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/VirtualStorageFolder.Windows.cs deleted file mode 100644 index 5cd041b3e8af..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/VirtualStorageFolder.Windows.cs +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Search; - -namespace Files.App.Utils.Storage -{ - public sealed partial class VirtualStorageFolder : BaseStorageFolder - { - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string DisplayType => Strings.Folder.GetLocalizedResource(); - public override string FolderRelativeId => $"0\\{Name}"; - - public override DateTimeOffset DateCreated { get; } - public override Windows.Storage.FileAttributes Attributes { get; } = Windows.Storage.FileAttributes.Directory; - public override IStorageItemExtraProperties Properties => new BaseBasicStorageItemExtraProperties(this); - - public VirtualStorageFolder(string cFileName) - { - Path = ""; - Name = cFileName; - } - - public override IAsyncOperation ToStorageFolderAsync() => throw new NotSupportedException(); - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - public override bool IsOfType(StorageItemTypes type) => type is StorageItemTypes.Folder; - - public override IAsyncOperation GetIndexedStateAsync() => Task.FromResult(IndexedState.NotIndexed).AsAsyncOperation(); - - public override IAsyncOperation GetParentAsync() => throw new NotSupportedException(); - - public override IAsyncOperation GetBasicPropertiesAsync() - { - return Task.FromResult(new BaseBasicProperties()).AsAsyncOperation(); - } - - public override IAsyncOperation GetItemAsync(string name) - { - return Task.FromResult(null).AsAsyncOperation(); - } - public override IAsyncOperation TryGetItemAsync(string name) - { - return Task.FromResult(null).AsAsyncOperation(); - } - public override IAsyncOperation?> GetItemsAsync() - { - return Task.FromResult?>(new List().AsReadOnly()) - .AsAsyncOperation(); - } - public override IAsyncOperation?> GetItemsAsync(uint startIndex, uint maxItemsToRetrieve) - => AsyncInfo.Run?>(async (cancellationToken) - => (await GetItemsAsync())!.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList()); - - public override IAsyncOperation GetFileAsync(string name) - => AsyncInfo.Run(async (cancellationToken) => await GetItemAsync(name) as BaseStorageFile); - public override IAsyncOperation?> GetFilesAsync() - => AsyncInfo.Run?>(async (cancellationToken) => (await GetItemsAsync())!.OfType().ToList()); - public override IAsyncOperation?> GetFilesAsync(CommonFileQuery query) - => AsyncInfo.Run?>(async (cancellationToken) => await GetFilesAsync()); - public override IAsyncOperation?> GetFilesAsync(CommonFileQuery query, uint startIndex, uint maxItemsToRetrieve) - => AsyncInfo.Run?>(async (cancellationToken) - => (await GetFilesAsync())!.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList()); - - public override IAsyncOperation GetFolderAsync(string name) - => AsyncInfo.Run(async (cancellationToken) => await GetItemAsync(name) as BaseStorageFolder); - public override IAsyncOperation?> GetFoldersAsync() - => AsyncInfo.Run?>(async (cancellationToken) => (await GetItemsAsync())!.OfType().ToList()); - public override IAsyncOperation?> GetFoldersAsync(CommonFolderQuery query) - => AsyncInfo.Run?>(async (cancellationToken) => await GetFoldersAsync()); - public override IAsyncOperation?> GetFoldersAsync(CommonFolderQuery query, uint startIndex, uint maxItemsToRetrieve) - => AsyncInfo.Run?>(async (cancellationToken) - => (await GetFoldersAsync())!.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList()); - - public override IAsyncOperation CreateFileAsync(string desiredName) - => CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists); - public override IAsyncOperation CreateFileAsync(string desiredName, CreationCollisionOption options) - => throw new NotSupportedException(); - - public override IAsyncOperation CreateFolderAsync(string desiredName) - => CreateFolderAsync(desiredName, CreationCollisionOption.FailIfExists); - public override IAsyncOperation CreateFolderAsync(string desiredName, CreationCollisionOption options) - => throw new NotSupportedException(); - public override IAsyncOperation MoveAsync(IStorageFolder destinationFolder) => throw new NotSupportedException(); - public override IAsyncOperation MoveAsync(IStorageFolder destinationFolder, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) - => RenameAsync(desiredName, NameCollisionOption.FailIfExists); - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - => throw new NotSupportedException(); - - public override IAsyncAction DeleteAsync() - => throw new NotSupportedException(); - public override IAsyncAction DeleteAsync(StorageDeleteOption option) => DeleteAsync(); - - public override bool AreQueryOptionsSupported(QueryOptions queryOptions) => false; - public override bool IsCommonFileQuerySupported(CommonFileQuery query) => false; - public override bool IsCommonFolderQuerySupported(CommonFolderQuery query) => false; - - public override StorageItemQueryResult CreateItemQuery() => throw new NotSupportedException(); - public override BaseStorageItemQueryResult CreateItemQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override StorageFileQueryResult CreateFileQuery() => throw new NotSupportedException(); - public override StorageFileQueryResult CreateFileQuery(CommonFileQuery query) => throw new NotSupportedException(); - public override BaseStorageFileQueryResult CreateFileQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override StorageFolderQueryResult CreateFolderQuery() => throw new NotSupportedException(); - public override StorageFolderQueryResult CreateFolderQuery(CommonFolderQuery query) => throw new NotSupportedException(); - public override BaseStorageFolderQueryResult CreateFolderQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - => Task.FromResult(null).AsAsyncOperation(); - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - => Task.FromResult(null).AsAsyncOperation(); - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - => Task.FromResult(null).AsAsyncOperation(); - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/VirtualStorageItem.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/VirtualStorageItem.Windows.cs deleted file mode 100644 index 9fe395051ddc..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/VirtualStorageItem.Windows.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Storage.FileSystem; - -namespace Files.App.Utils.Storage -{ - /// - /// Implements IStorageItem, allowing us to get an instance of IStorageItem for a ListedItem - /// representing a standard filesystem item. As such, VirtualStorageItem does not support hidden, - /// shortcut, or link items. - /// - public sealed partial class VirtualStorageItem : IStorageItem - { - private static BasicProperties? props; - - public Windows.Storage.FileAttributes Attributes { get; init; } - - public DateTimeOffset DateCreated { get; init; } - - public string Name { get; init; } = null!; - - public string Path { get; init; } = null!; - - private VirtualStorageItem() { } - - public static VirtualStorageItem FromListedItem(ListedItem item) - { - return new VirtualStorageItem() - { - Name = item.ItemNameRaw!, - Path = item.ItemPath!, - DateCreated = item.ItemDateCreatedReal, - Attributes = item.IsArchive || item.PrimaryItemAttribute == StorageItemTypes.File ? Windows.Storage.FileAttributes.Normal : Windows.Storage.FileAttributes.Directory - }; - } - - public static unsafe VirtualStorageItem? FromPath(string path) - { - WIN32_FIND_DATAW findData = default; - using FindCloseSafeHandle hFile = PInvoke.FindFirstFileEx(path, FINDEX_INFO_LEVELS.FindExInfoBasic, &findData, FINDEX_SEARCH_OPS.FindExSearchNameMatch, FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - if (!hFile.IsInvalid) - { - // https://learn.microsoft.com/openspecs/windows_protocols/ms-fscc/c8e77b37-3909-4fe6-a4ea-2b9d423b1ee4 - bool isReparsePoint = ((System.IO.FileAttributes)findData.dwFileAttributes & System.IO.FileAttributes.ReparsePoint) == System.IO.FileAttributes.ReparsePoint; - bool isSymlink = isReparsePoint && findData.dwReserved0 == PInvoke.IO_REPARSE_TAG_SYMLINK; - bool isHidden = ((System.IO.FileAttributes)findData.dwFileAttributes & System.IO.FileAttributes.Hidden) == System.IO.FileAttributes.Hidden; - bool isDirectory = ((System.IO.FileAttributes)findData.dwFileAttributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory; - - if (!(isHidden && isSymlink)) - { - DateTime itemCreatedDate; - - try - { - PInvoke.FileTimeToSystemTime(findData.ftCreationTime, out SYSTEMTIME systemCreatedDateOutput); - itemCreatedDate = systemCreatedDateOutput.ToDateTime(); - } - catch (ArgumentException) - { - // Invalid date means invalid findData, do not add to list - return null; - } - - return new VirtualStorageItem() - { - Name = findData.cFileName.ToString(), - Path = path, - DateCreated = itemCreatedDate, - Attributes = isDirectory ? Windows.Storage.FileAttributes.Directory : Windows.Storage.FileAttributes.Normal - }; - } - } - - return null; - } - - private async void StreamedFileWriterAsync(StreamedFileDataRequest request) - { - try - { - await using (var stream = request.AsStreamForWrite()) - { - await stream.FlushAsync(); - } - request.Dispose(); - } - catch (Exception) - { - request.FailAndClose(StreamedFileFailureMode.Incomplete); - } - } - - public IAsyncAction RenameAsync(string desiredName) - { - throw new NotImplementedException(); - } - - public IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - { - throw new NotImplementedException(); - } - - public IAsyncAction DeleteAsync() - { - throw new NotImplementedException(); - } - - public IAsyncAction DeleteAsync(StorageDeleteOption option) - { - throw new NotImplementedException(); - } - - public IAsyncOperation GetBasicPropertiesAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - async Task GetFakeBasicProperties() - { - var streamedFile = await StorageFile.CreateStreamedFileAsync(Name, StreamedFileWriterAsync, null); - return await streamedFile.GetBasicPropertiesAsync(); - } - return props ?? (props = await GetFakeBasicProperties()); - }); - } - - public bool IsOfType(StorageItemTypes type) - { - return Attributes.HasFlag(Windows.Storage.FileAttributes.Directory) ? type == StorageItemTypes.Folder : type == StorageItemTypes.File; - } - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.Windows.cs deleted file mode 100644 index 59ba26636d8e..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.Windows.cs +++ /dev/null @@ -1,848 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using ICSharpCode.SharpZipLib.Zip; -using SevenZip; -using System.IO; -using System.Text; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Streams; -using Windows.Win32; -using IO = System.IO; - -namespace Files.App.Utils.Storage -{ - public sealed partial class ZipStorageFile : BaseStorageFile, IPasswordProtectedItem - { - private readonly string containerPath; - private readonly BaseStorageFile? backingFile; - - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string ContentType => "application/octet-stream"; - public override string FileType => IO.Path.GetExtension(Name); - public override string FolderRelativeId => $"0\\{Name}"; - - public override string DisplayType - { - get - { - var itemType = Strings.File.GetLocalizedResource(); - if (Name.Contains('.', StringComparison.Ordinal)) - { - itemType = FileType.Trim('.') + " " + itemType; - } - return itemType; - } - } - - public override DateTimeOffset DateCreated { get; } - public override Windows.Storage.FileAttributes Attributes => Windows.Storage.FileAttributes.Normal | Windows.Storage.FileAttributes.ReadOnly; - - private IStorageItemExtraProperties? properties; - public override IStorageItemExtraProperties Properties => properties ??= new BaseBasicStorageItemExtraProperties(this); - - public StorageCredential? Credentials { get; set; } = new(); - private string Password => Credentials?.Password - ?? throw new InvalidOperationException("Archive credentials are not available."); - - internal Encoding? CurrentEncoding { get; set; } - - public Func>? PasswordRequestedCallback { get; set; } - - public ZipStorageFile(string path, string containerPath) - { - Name = IO.Path.GetFileName(path.TrimEnd('\\', '/')); - Path = path; - this.containerPath = containerPath; - } - public ZipStorageFile(string path, string containerPath, BaseStorageFile? backingFile) : this(path, containerPath) - => this.backingFile = backingFile; - public ZipStorageFile(string path, string containerPath, ArchiveFileInfo entry) : this(path, containerPath) - => DateCreated = entry.CreationTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.CreationTime; - public ZipStorageFile(string path, string containerPath, ArchiveFileInfo entry, BaseStorageFile? backingFile) : this(path, containerPath, entry) - => this.backingFile = backingFile; - - public override IAsyncOperation ToStorageFileAsync() - => StorageFile.CreateStreamedFileAsync( - Name, - CurrentEncoding is not null && Path != containerPath - ? ZipDataStreamingHandlerWithEncoding(Path) - : ZipDataStreamingHandler(Path), - null - ); - - public static IAsyncOperation FromPathAsync(string path) - { - var containerPath = ZipStorageFolder.GetContainerPath(path); - if (containerPath is null) - return Task.FromResult(null).AsAsyncOperation(); - - if (path == containerPath) - return Task.FromResult(null).AsAsyncOperation(); // Root - - if (CheckAccess(containerPath)) - { - var file = new ZipStorageFile(path, containerPath); - if (ZipStorageFolder.TryGetEncodingForContainerPath(containerPath, out var encoding)) - file.CurrentEncoding = encoding; - return Task.FromResult(file).AsAsyncOperation(); - } - return Task.FromResult(null).AsAsyncOperation(); - } - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - public override bool IsOfType(StorageItemTypes type) => type is StorageItemTypes.File; - - public override IAsyncOperation GetParentAsync() => throw new NotSupportedException(); - public override IAsyncOperation GetBasicPropertiesAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (CurrentEncoding is not null && Path != containerPath) - return await GetBasicPropertiesWithEncodingAsync(); - - return await GetBasicProperties(); - }); - } - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode) - { - if (CurrentEncoding is not null && Path != containerPath) - return OpenWithEncodingAsync(accessMode); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - bool rw = accessMode is FileAccessMode.ReadWrite; - if (Path == containerPath) - { - if (backingFile is not null) - { - return await backingFile.OpenAsync(accessMode); - } - - var file = Win32Helper.OpenFileForRead(containerPath, rw); - return file.IsInvalid ? null : new FileStream(file, rw ? FileAccess.ReadWrite : FileAccess.Read).AsRandomAccessStream(); - } - - if (!rw) - { - SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - - if (entry.FileName is not null) - { - var ms = new MemoryStream(); - await zipFile.ExtractFileAsync(entry.Index, ms); - ms.Position = 0; - return new NonSeekableRandomAccessStreamForRead(ms, entry.Size) - { - DisposeCallback = () => zipFile.Dispose() - }; - } - return null; - } - - throw new NotSupportedException("Can't open zip file as RW"); - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncOperation OpenWithEncodingAsync(FileAccessMode accessMode) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - bool rw = accessMode is FileAccessMode.ReadWrite; - if (rw) - throw new NotSupportedException("Can't open zip file as RW"); - - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetName = GetEntryRelativePath(); - - foreach (ZipEntry entry in zipFile) - { - if (!entry.IsFile) - continue; - - if (string.Equals(entry.Name.Replace('\\', '/'), targetName, StringComparison.OrdinalIgnoreCase)) - { - var ms = new MemoryStream(); - using (var zipStream = zipFile.GetInputStream(entry)) - { - zipStream.CopyTo(ms); - } - ms.Position = 0; - return new NonSeekableRandomAccessStreamForRead(ms, (ulong)entry.Size); - } - } - - return null; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) - => OpenAsync(accessMode); - - public override IAsyncOperation OpenReadAsync() - { - if (CurrentEncoding is not null && Path != containerPath) - return OpenReadWithEncodingAsync(); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - if (Path == containerPath) - { - if (backingFile is not null) - { - return await backingFile.OpenReadAsync(); - } - - var hFile = Win32Helper.OpenFileForRead(containerPath); - return hFile.IsInvalid ? null : new StreamWithContentType(new FileStream(hFile, FileAccess.Read).AsRandomAccessStream()); - } - - SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - if (entry.FileName is null) - { - return null; - } - - var ms = new MemoryStream(); - await zipFile.ExtractFileAsync(entry.Index, ms); - ms.Position = 0; - var nsStream = new NonSeekableRandomAccessStreamForRead(ms, entry.Size) - { - DisposeCallback = () => zipFile.Dispose() - }; - return new StreamWithContentType(nsStream); - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncOperation OpenReadWithEncodingAsync() - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetName = GetEntryRelativePath(); - - foreach (ZipEntry entry in zipFile) - { - if (!entry.IsFile) - continue; - - if (string.Equals(entry.Name.Replace('\\', '/'), targetName, StringComparison.OrdinalIgnoreCase)) - { - var ms = new MemoryStream(); - using (var zipStream = zipFile.GetInputStream(entry)) - { - zipStream.CopyTo(ms); - } - ms.Position = 0; - var nsStream = new NonSeekableRandomAccessStreamForRead(ms, (ulong)entry.Size); - return new StreamWithContentType(nsStream); - } - } - return null; - - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation OpenSequentialReadAsync() - { - if (CurrentEncoding is not null && Path != containerPath) - return OpenSequentialReadWithEncodingAsync(); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - if (Path == containerPath) - { - if (backingFile is not null) - { - return await backingFile.OpenSequentialReadAsync(); - } - - var hFile = Win32Helper.OpenFileForRead(containerPath); - return hFile.IsInvalid ? null : new FileStream(hFile, FileAccess.Read).AsInputStream(); - } - - SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - if (entry.FileName is null) - { - return null; - } - - var ms = new MemoryStream(); - await zipFile.ExtractFileAsync(entry.Index, ms); - ms.Position = 0; - return new NonSeekableRandomAccessStreamForRead(ms, entry.Size) - { - DisposeCallback = () => zipFile.Dispose() - }; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncOperation OpenSequentialReadWithEncodingAsync() - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetName = GetEntryRelativePath(); - - foreach (ZipEntry entry in zipFile) - { - if (!entry.IsFile) - continue; - - if (string.Equals(entry.Name.Replace('\\', '/'), targetName, StringComparison.OrdinalIgnoreCase)) - { - var ms = new MemoryStream(); - using (var zipStream = zipFile.GetInputStream(entry)) - { - zipStream.CopyTo(ms); - } - ms.Position = 0; - return new NonSeekableRandomAccessStreamForRead(ms, (ulong)entry.Size); - } - } - - return null; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation OpenTransactedWriteAsync() - => throw new NotSupportedException(); - public override IAsyncOperation OpenTransactedWriteAsync(StorageOpenOptions options) - => throw new NotSupportedException(); - - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder) - => CopyAsync(destinationFolder, Name, NameCollisionOption.FailIfExists); - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName) - => CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists); - public override IAsyncOperation CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - if (CurrentEncoding is not null && Path != containerPath) - return CopyWithEncodingAsync(destinationFolder, desiredNewName, option); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - if (entry.FileName is null) - { - return null; - } - - var destFolder = destinationFolder.AsBaseStorageFolder() - ?? throw new NotSupportedException("The destination folder type is not supported."); - - if (destFolder is ICreateFileWithStream cwsf) - { - var ms = new MemoryStream(); - await zipFile.ExtractFileAsync(entry.Index, ms); - ms.Position = 0; - using var inStream = new NonSeekableRandomAccessStreamForRead(ms, entry.Size); - return await cwsf.CreateFileAsync(inStream.AsStreamForRead(), desiredNewName, option.Convert()); - } - else - { - var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert()) - ?? throw new IOException($"Failed to create destination file '{desiredNewName}'."); - - await using var outStream = await destFile.OpenStreamForWriteAsync(); - await SafetyExtensions.WrapAsync(() => zipFile.ExtractFileAsync(entry.Index, outStream), async (_, exception) => - { - await destFile.DeleteAsync(); - throw exception; - }); - return destFile; - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncOperation CopyWithEncodingAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetName = GetEntryRelativePath(); - - var entry = zipFile.Cast().FirstOrDefault(x => x.IsFile && string.Equals(x.Name.Replace('\\', '/'), targetName, StringComparison.OrdinalIgnoreCase)); - if (entry is null) - { - return null; - } - - var destFolder = destinationFolder.AsBaseStorageFolder() - ?? throw new NotSupportedException("The destination folder type is not supported."); - if (destFolder is ICreateFileWithStream cwsf) - { - var ms = new MemoryStream(); - using var zipStream = zipFile.GetInputStream(entry); - zipStream.CopyTo(ms); - ms.Position = 0; - using var inStream = new NonSeekableRandomAccessStreamForRead(ms, (ulong)entry.Size); - return await cwsf.CreateFileAsync(inStream.AsStreamForRead(), desiredNewName, option.Convert()); - } - else - { - var destFile = await destFolder.CreateFileAsync(desiredNewName, option.Convert()) - ?? throw new IOException($"Failed to create destination file '{desiredNewName}'."); - await using var outStream = await destFile.OpenStreamForWriteAsync(); - using var zipStream = zipFile.GetInputStream(entry); - zipStream.CopyTo(outStream); - return destFile; - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) - { - if (CurrentEncoding is not null && Path != containerPath) - return CopyAndReplaceWithEncodingAsync(fileToReplace); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () => - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return; - } - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - if (entry.FileName is null) - { - return; - } - - await using (var outStream = await fileToReplace.OpenStreamForWriteAsync()) - { - outStream.SetLength(0); - await zipFile.ExtractFileAsync(entry.Index, outStream); - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncAction CopyAndReplaceWithEncodingAsync(IStorageFile fileToReplace) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetName = GetEntryRelativePath(); - - foreach (ZipEntry entry in zipFile) - { - if (!entry.IsFile) - continue; - - if (string.Equals(entry.Name.Replace('\\', '/'), targetName, StringComparison.OrdinalIgnoreCase)) - { - await using (var outStream = await fileToReplace.OpenStreamForWriteAsync()) - using (var zipStream = zipFile.GetInputStream(entry)) - { - outStream.SetLength(0); - zipStream.CopyTo(outStream); - } - return; - } - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder) - => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) - => throw new NotSupportedException(); - public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) - => throw new NotSupportedException(); - public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) - => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) => RenameAsync(desiredName, NameCollisionOption.FailIfExists); - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () => - { - if (Path == containerPath) - { - if (backingFile is not null) - { - await backingFile.RenameAsync(desiredName, option); - } - else - { - var parentPath = IO.Path.GetDirectoryName(Path) ?? throw new InvalidOperationException("The archive path has no parent."); - var fileName = IO.Path.Combine(parentPath, desiredName); - PInvoke.MoveFileFromApp(Path, fileName); - } - } - else - { - var index = await FetchZipIndex(); - if (index < 0) - { - return; - } - using (var ms = new MemoryStream()) - { - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for reading.")) - { - SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append }; - compressor.CustomParameters.Add("cu", "on"); - compressor.SetFormatFromExistingArchive(archiveStream); - var parentPath = IO.Path.GetDirectoryName(Path) ?? throw new InvalidOperationException("The archive entry has no parent."); - var fileName = IO.Path.GetRelativePath(containerPath, IO.Path.Combine(parentPath, desiredName)); - await compressor.ModifyArchiveAsync(archiveStream, new Dictionary() { { index, fileName } }, Password, ms); - } - - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for writing.")) - { - ms.Position = 0; - await ms.CopyToAsync(archiveStream); - await ms.FlushAsync(); - archiveStream.SetLength(archiveStream.Position); - } - } - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncAction DeleteAsync() => DeleteAsync(StorageDeleteOption.Default); - public override IAsyncAction DeleteAsync(StorageDeleteOption option) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () => - { - if (Path == containerPath) - { - if (backingFile is not null) - { - await backingFile.DeleteAsync(); - } - else if (option == StorageDeleteOption.PermanentDelete) - { - PInvoke.DeleteFileFromApp(Path); - } - else - { - throw new NotSupportedException("Moving to recycle bin is not supported."); - } - } - else - { - var index = await FetchZipIndex(); - if (index < 0) - { - return; - } - using (var ms = new MemoryStream()) - { - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for reading.")) - { - SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append }; - compressor.CustomParameters.Add("cu", "on"); - compressor.SetFormatFromExistingArchive(archiveStream); - await compressor.ModifyArchiveAsync(archiveStream, new Dictionary() { { index, null } }, Password, ms); - } - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for writing.")) - { - ms.Position = 0; - await ms.CopyToAsync(archiveStream); - await ms.FlushAsync(); - archiveStream.SetLength(archiveStream.Position); - } - } - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - => Task.FromResult(null).AsAsyncOperation(); - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - => Task.FromResult(null).AsAsyncOperation(); - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - => Task.FromResult(null).AsAsyncOperation(); - - private string GetEntryRelativePath() - { - var relative = Path.Substring(containerPath.Length).Trim('\\', '/'); - return relative.Replace('\\', '/'); - } - - private static bool CheckAccess(string path) - { - try - { - var hFile = Win32Helper.OpenFileForRead(path); - if (hFile.IsInvalid) - { - return false; - } - using (SevenZipExtractor zipFile = new SevenZipExtractor(new FileStream(hFile, FileAccess.Read))) - { - //zipFile.IsStreamOwner = true; - return zipFile.ArchiveFileData is not null; - } - } - catch (SevenZipOpenFailedException ex) - { - return ex.Result == OperationResult.WrongPassword; - } - catch - { - return false; - } - } - - private async Task FetchZipIndex() - { - using (SevenZipExtractor? zipFile = await OpenZipFileAsync()) - { - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return -1; - } - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - if (entry.FileName is not null) - { - return entry.Index; - } - return -1; - } - } - - private async Task GetBasicProperties() - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return new BaseBasicProperties(); - } - - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - - return entry.FileName is null - ? new BaseBasicProperties() - : new ZipFileBasicProperties(entry); - } - - private Task GetBasicPropertiesWithEncodingAsync() - { - return Task.Run(() => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetName = GetEntryRelativePath(); - - foreach (ZipEntry entry in zipFile) - { - if (!entry.IsFile) - continue; - - if (string.Equals(entry.Name.Replace('\\', '/'), targetName, StringComparison.OrdinalIgnoreCase)) - return new ZipFileBasicPropertiesWithEncoding(entry); - } - - return new BaseBasicProperties(); - }); - } - - private IAsyncOperation OpenZipFileAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - var zipFile = await OpenZipFileAsync(FileAccessMode.Read); - return zipFile is not null ? new SevenZipExtractor(zipFile, Password) : null; - }); - } - - private IAsyncOperation OpenZipFileAsync(FileAccessMode accessMode) - { - return AsyncInfo.Run(async (cancellationToken) => - { - bool readWrite = accessMode == FileAccessMode.ReadWrite; - if (backingFile is not null) - { - var stream = await backingFile.OpenAsync(accessMode); - return stream?.AsStream(); - } - else - { - var hFile = Win32Helper.OpenFileForRead(containerPath, readWrite); - return hFile.IsInvalid ? null : new FileStream(hFile, readWrite ? FileAccess.ReadWrite : FileAccess.Read); - } - }); - } - - private StreamedFileDataRequestedHandler ZipDataStreamingHandler(string name) - { - return async request => - { - try - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable); - return; - } - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == name); - if (entry.FileName is null) - { - request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable); - } - else - { - await using (var outStream = request.AsStreamForWrite()) - { - await zipFile.ExtractFileAsync(entry.Index, outStream); - } - request.Dispose(); - } - } - catch - { - request.FailAndClose(StreamedFileFailureMode.Failed); - } - }; - } - - private StreamedFileDataRequestedHandler ZipDataStreamingHandlerWithEncoding(string name) - { - return async request => - { - try - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var entry = zipFile.Cast().FirstOrDefault( - x => x.IsFile - && string.Equals( - System.IO.Path.Combine( - containerPath, x.Name.Replace('/', '\\') - ), - name, - StringComparison.OrdinalIgnoreCase - ) - ); - if (entry is not null && entry.IsFile) - { - using var zipStream = zipFile.GetInputStream(entry); - await using (var outStream = request.AsStreamForWrite()) - { - await zipStream.CopyToAsync(outStream); - } - request.Dispose(); - } - else - { - request.FailAndClose(StreamedFileFailureMode.CurrentlyUnavailable); - } - } - catch - { - request.FailAndClose(StreamedFileFailureMode.Failed); - } - }; - } - - private sealed partial class ZipFileBasicProperties : BaseBasicProperties - { - private ArchiveFileInfo entry; - - public ZipFileBasicProperties(ArchiveFileInfo entry) => this.entry = entry; - - public override DateTimeOffset DateModified => entry.LastWriteTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.LastWriteTime; - - public override DateTimeOffset DateCreated => entry.CreationTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.CreationTime; - - public override ulong Size => entry.Size; - } - - private sealed partial class ZipFileBasicPropertiesWithEncoding : BaseBasicProperties - { - private ZipEntry entry; - - public ZipFileBasicPropertiesWithEncoding(ZipEntry entry) => this.entry = entry; - - public override DateTimeOffset DateModified => entry.DateTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.DateTime; - - public override DateTimeOffset DateCreated => DateTimeOffset.MinValue; - - public override ulong Size => (ulong)entry.Size; - } - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.cs b/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.cs index 98f9b2ed1949..7399c46c8bd9 100644 --- a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.cs +++ b/src/Files.App/Utils/Storage/StorageItems/ZipStorageFile.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; @@ -13,4 +12,3 @@ public abstract class ZipStorageFile : BaseStorageFile public static IAsyncOperation FromPathAsync(string path) => Task.FromResult(null).AsAsyncOperation(); } } -#endif diff --git a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.Windows.cs b/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.Windows.cs deleted file mode 100644 index b72ef63f46ab..000000000000 --- a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.Windows.cs +++ /dev/null @@ -1,898 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using ICSharpCode.SharpZipLib.Zip; -using SevenZip; -using System.Collections.Concurrent; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Text; -using Windows.ApplicationModel; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Search; -using Windows.Win32; -using IO = System.IO; - -namespace Files.App.Utils.Storage -{ - public sealed partial class ZipStorageFolder : BaseStorageFolder, ICreateFileWithStream, IPasswordProtectedItem - { - private readonly string containerPath; - private BaseStorageFile? backingFile; - - private Encoding? _currentEncoding; - - // Maps container paths to their configured encoding. - // - Key missing: encoding not yet set; detection required. - // - Value null: archive opened with system default encoding. - // - Value set: archive opened with the specified encoding. - private static readonly ConcurrentDictionary _encodingByContainerPath = new(StringComparer.OrdinalIgnoreCase); - - /// - /// Gets or sets the encoding to use when browsing this ZIP file. - /// When set, SharpZipLib is used instead of SevenZipSharp. - /// - internal Encoding? CurrentEncoding - { - get => _currentEncoding; - set - { - _currentEncoding = value; - _encodingByContainerPath[containerPath] = value; - } - } - - internal static bool TryGetEncodingForContainerPath(string containerPath, out Encoding? encoding) - => _encodingByContainerPath.TryGetValue(containerPath, out encoding); - - internal static void SetEncodingForContainerPath(string containerPath, Encoding? encoding) - { - _encodingByContainerPath[containerPath] = encoding; - } - - public override string Path { get; } - public override string Name { get; } - public override string DisplayName => Name; - public override string DisplayType => Strings.Folder.GetLocalizedResource(); - public override string FolderRelativeId => $"0\\{Name}"; - - public override DateTimeOffset DateCreated { get; } - public override Windows.Storage.FileAttributes Attributes => Windows.Storage.FileAttributes.Directory; - public override IStorageItemExtraProperties Properties => new BaseBasicStorageItemExtraProperties(this); - - public StorageCredential? Credentials { get; set; } = new(); - private string Password => Credentials?.Password - ?? throw new InvalidOperationException("Archive credentials are not available."); - - public Func>? PasswordRequestedCallback { get; set; } - - public ZipStorageFolder(string path, string containerPath) - { - Name = IO.Path.GetFileName(path.TrimEnd('\\', '/')); - Path = path; - this.containerPath = containerPath; - _encodingByContainerPath.TryGetValue(containerPath, out _currentEncoding); - } - public ZipStorageFolder(string path, string containerPath, BaseStorageFile? backingFile) : this(path, containerPath) - => this.backingFile = backingFile; - public ZipStorageFolder(string path, string containerPath, ArchiveFileInfo entry) : this(path, containerPath) - => DateCreated = entry.CreationTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.CreationTime; - public ZipStorageFolder(BaseStorageFile backingFile) - { - ArgumentException.ThrowIfNullOrEmpty(backingFile.Path); - Name = IO.Path.GetFileName(backingFile.Path.TrimEnd('\\', '/')); - Path = backingFile.Path; - this.containerPath = backingFile.Path; - this.backingFile = backingFile; - _encodingByContainerPath.TryGetValue(containerPath, out _currentEncoding); - } - public ZipStorageFolder(string path, string containerPath, ArchiveFileInfo entry, BaseStorageFile? backingFile) : this(path, containerPath, entry) - => this.backingFile = backingFile; - - public static string? GetContainerPath(string path) - { - if (!FileExtensionHelpers.IsBrowsableZipFile(path, out var ext)) - return null; - - var marker = path.IndexOf(ext, StringComparison.OrdinalIgnoreCase); - if (marker is -1) - return null; - - return path.Substring(0, marker + ext.Length); - } - - public static bool IsZipPath([NotNullWhen(true)] string? path, bool includeRoot = true) - { - if (path is null || !FileExtensionHelpers.IsBrowsableZipFile(path, out var ext)) - { - return false; - } - var marker = path.IndexOf(ext, StringComparison.OrdinalIgnoreCase); - if (marker is -1) - { - return false; - } - marker += ext.Length; - // If IO.Path.Exists returns true, it is not a zip path but a normal directory path that contains ".zip". - return (marker == path.Length && includeRoot && !IO.Path.Exists(path + "\\")) - || (marker < path.Length && path[marker] is '\\' && !IO.Path.Exists(path)); - } - - public async Task GetUncompressedSize() - { - long uncompressedSize = 0; - using SevenZipExtractor? zipFile = await FilesystemTasks.WrapNullable(async () => - { - var arch = await OpenZipFileAsync(); - return arch?.ArchiveFileData is null ? null : arch; // Force load archive (1665013614u) - }); - - if (zipFile is not null) - { - foreach (var info in zipFile.ArchiveFileData.Where(x => !x.IsDirectory)) - { - uncompressedSize += (long)info.Size; - } - } - - return uncompressedSize; - } - - private static ConcurrentDictionary> defaultAppDict = new(); - public static async Task CheckDefaultZipApp(string filePath) - { - Func> queryFileAssoc = async () => - { - var assoc = await Win32Helper.GetDefaultFileAssociationAsync(filePath); - if (assoc is not null) - { - return Constants.Distributions.KnownAppNames.Any(x => assoc.StartsWith(x, StringComparison.OrdinalIgnoreCase)) - || assoc == Package.Current.Id.FamilyName - || assoc.EndsWith("Files.exe", StringComparison.OrdinalIgnoreCase) - || assoc.Equals(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"), StringComparison.OrdinalIgnoreCase); - } - return true; - }; - var ext = IO.Path.GetExtension(filePath)?.ToLowerInvariant(); - return await defaultAppDict.GetAsync(ext ?? "", queryFileAssoc); - } - - public static IAsyncOperation FromPathAsync(string path) - { - var containerPath = GetContainerPath(path); - if (containerPath is not null && CheckAccess(containerPath)) - { - return Task.FromResult(new ZipStorageFolder(path, containerPath)).AsAsyncOperation(); - } - return Task.FromResult(null).AsAsyncOperation(); - } - - public static IAsyncOperation FromStorageFileAsync(BaseStorageFile file) - => AsyncInfo.Run(async (cancellationToken) => await CheckAccess(file) ? new ZipStorageFolder(file) : null); - - public override IAsyncOperation ToStorageFolderAsync() => throw new NotSupportedException(); - - public override bool IsEqual(IStorageItem item) => item?.Path == Path; - public override bool IsOfType(StorageItemTypes type) => type == StorageItemTypes.Folder; - - public override IAsyncOperation GetIndexedStateAsync() => Task.FromResult(IndexedState.NotIndexed).AsAsyncOperation(); - - public override IAsyncOperation GetParentAsync() => throw new NotSupportedException(); - - private async Task GetBasicProperties() - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return new BaseBasicProperties(); - } - //zipFile.IsStreamOwner = true; - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path); - return entry.FileName is null - ? new BaseBasicProperties() - : new ZipFolderBasicProperties(entry); - } - private Task GetBasicPropertiesWithEncodingAsync() - { - return Task.Run(() => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var normalizedTarget = Path.TrimEnd('\\', '/'); - - foreach (ZipEntry entry in zipFile) - { - var entryPath = System.IO.Path.Combine(System.IO.Path.GetFullPath(containerPath), entry.Name.Replace("/", "\\")); - var normalizedEntry = entryPath.TrimEnd('\\', '/'); - - if (normalizedEntry.Equals(normalizedTarget, StringComparison.OrdinalIgnoreCase)) - return new ZipFolderBasicPropertiesWithEncoding(entry); - } - - return new BaseBasicProperties(); - }); - } - - public override IAsyncOperation GetBasicPropertiesAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (Path == containerPath) - { - var zipFile = new SystemStorageFile(await StorageFile.GetFileFromPathAsync(Path)); - return await zipFile.GetBasicPropertiesAsync(); - } - - if (CurrentEncoding is not null) - return await GetBasicPropertiesWithEncodingAsync(); - - return await GetBasicProperties(); - }); - } - - public override IAsyncOperation GetItemAsync(string name) - { - if (CurrentEncoding is not null) - return GetItemWithEncodingAsync(name); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - //zipFile.IsStreamOwner = true; - - var filePath = System.IO.Path.Combine(Path, name); - - var entry = zipFile.GetArchiveFileData(containerPath).FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == filePath); - if (entry.FileName is null) - { - return null; - } - - if (entry.IsDirectory) - { - var folder = new ZipStorageFolder(filePath, containerPath, entry, backingFile); - ((IPasswordProtectedItem)folder).CopyFrom(this); - return folder; - } - - var file = new ZipStorageFile(filePath, containerPath, entry, backingFile); - ((IPasswordProtectedItem)file).CopyFrom(this); - file.CurrentEncoding = CurrentEncoding; - return file; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncOperation GetItemWithEncodingAsync(string name) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var targetPath = System.IO.Path.Combine(Path, name); - var normalizedTarget = targetPath.TrimEnd('\\', '/'); - bool foundChild = false; - - foreach (ZipEntry entry in zipFile) - { - var entryPath = System.IO.Path.Combine(System.IO.Path.GetFullPath(containerPath), entry.Name.Replace("/", "\\")); - var normalizedEntry = entryPath.TrimEnd('\\', '/'); - - if (normalizedEntry.Equals(normalizedTarget, StringComparison.OrdinalIgnoreCase)) - { - if (entry.IsDirectory) - { - var folder = new ZipStorageFolder(targetPath, containerPath, backingFile); - ((IPasswordProtectedItem)folder).CopyFrom(this); - return folder; - } - else - { - var file = new ZipStorageFile(targetPath, containerPath, backingFile); - ((IPasswordProtectedItem)file).CopyFrom(this); - file.CurrentEncoding = CurrentEncoding; - return file; - } - } - - if (!foundChild && normalizedEntry.StartsWith(normalizedTarget + "\\", StringComparison.OrdinalIgnoreCase)) - foundChild = true; - } - - // No exact match found; check if target is an implicit directory - if (foundChild) - { - var folder = new ZipStorageFolder(targetPath, containerPath, backingFile); - ((IPasswordProtectedItem)folder).CopyFrom(this); - return folder; - } - - return null; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation TryGetItemAsync(string name) - { - return AsyncInfo.Run(async (cancellationToken) => - { - try - { - return await GetItemAsync(name); - } - catch - { - return null; - } - }); - } - public override IAsyncOperation?> GetItemsAsync() - { - if (CurrentEncoding is not null) - return GetItemsWithEncodingAsync(); - - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap?>(async () => - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - //zipFile.IsStreamOwner = true; - var items = new List(); - foreach (var entry in zipFile.GetArchiveFileData(containerPath)) // Returns all items recursively - { - string winPath = System.IO.Path.Combine(System.IO.Path.GetFullPath(containerPath), entry.FileName); - if (winPath.StartsWith(Path.WithEnding("\\"), StringComparison.Ordinal)) // Child of self - { - var split = winPath.Substring(Path.Length).Split('\\', StringSplitOptions.RemoveEmptyEntries); - if (split.Length > 0) - { - if (entry.IsDirectory || split.Length > 1) // Not all folders have a ZipEntry - { - var itemPath = System.IO.Path.Combine(Path, split[0]); - if (!items.Any(x => x.Path == itemPath)) - { - var folder = new ZipStorageFolder(itemPath, containerPath, entry, backingFile); - ((IPasswordProtectedItem)folder).CopyFrom(this); - items.Add(folder); - } - } - else - { - var file = new ZipStorageFile(winPath, containerPath, entry, backingFile); - ((IPasswordProtectedItem)file).CopyFrom(this); - file.CurrentEncoding = CurrentEncoding; - items.Add(file); - } - } - } - } - return items; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private IAsyncOperation?> GetItemsWithEncodingAsync() - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap?>(async () => - { - var encoding = CurrentEncoding - ?? throw new InvalidOperationException("The archive encoding has not been initialized."); - using var zipFile = new ZipFile(containerPath, StringCodec.FromEncoding(encoding)); - - if (!string.IsNullOrEmpty(Password)) - zipFile.Password = Password; - - var items = new List(); - var dirPrefix = Path.WithEnding("\\"); - - foreach (ZipEntry entry in zipFile) - { - string winPath = System.IO.Path.Combine(System.IO.Path.GetFullPath(containerPath), entry.Name.Replace("/", "\\")); - if (!winPath.StartsWith(dirPrefix, StringComparison.Ordinal)) - continue; - - var split = winPath.Substring(Path.Length).Split('\\', StringSplitOptions.RemoveEmptyEntries); - if (split.Length <= 0) - continue; - - if (entry.IsDirectory || split.Length > 1) // Not all folders have a ZipEntry - { - var itemPath = System.IO.Path.Combine(Path, split[0]); - if (!items.Any(x => x.Path == itemPath)) - { - var folder = new ZipStorageFolder(itemPath, containerPath, backingFile); - ((IPasswordProtectedItem)folder).CopyFrom(this); - items.Add(folder); - } - } - else - { - var file = new ZipStorageFile(winPath, containerPath, backingFile); - ((IPasswordProtectedItem)file).CopyFrom(this); - file.CurrentEncoding = CurrentEncoding; - items.Add(file); - } - - } - return items; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation?> GetItemsAsync(uint startIndex, uint maxItemsToRetrieve) - => AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetItemsAsync() - ?? throw new InvalidDataException($"The archive '{containerPath}' could not be read."); - return items.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList(); - }); - - public override IAsyncOperation GetFileAsync(string name) - => AsyncInfo.Run(async (cancellationToken) => await GetItemAsync(name) as ZipStorageFile); - public override IAsyncOperation?> GetFilesAsync() - => AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetItemsAsync(); - return items?.OfType().ToList(); - }); - public override IAsyncOperation?> GetFilesAsync(CommonFileQuery query) - => AsyncInfo.Run?>(async (cancellationToken) => await GetFilesAsync()); - public override IAsyncOperation?> GetFilesAsync(CommonFileQuery query, uint startIndex, uint maxItemsToRetrieve) - => AsyncInfo.Run?>(async (cancellationToken) => - { - var files = await GetFilesAsync() - ?? throw new InvalidDataException($"The archive '{containerPath}' could not be read."); - return files.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList(); - }); - - public override IAsyncOperation GetFolderAsync(string name) - => AsyncInfo.Run(async (cancellationToken) => await GetItemAsync(name) as ZipStorageFolder); - public override IAsyncOperation?> GetFoldersAsync() - => AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetItemsAsync(); - return items?.OfType().ToList(); - }); - public override IAsyncOperation?> GetFoldersAsync(CommonFolderQuery query) - => AsyncInfo.Run?>(async (cancellationToken) => await GetFoldersAsync()); - public override IAsyncOperation?> GetFoldersAsync(CommonFolderQuery query, uint startIndex, uint maxItemsToRetrieve) - { - return AsyncInfo.Run?>(async (cancellationToken) => - { - var items = await GetFoldersAsync() - ?? throw new InvalidDataException($"The archive '{containerPath}' could not be read."); - return items.Skip((int)startIndex).Take((int)maxItemsToRetrieve).ToList(); - }); - } - - public override IAsyncOperation CreateFileAsync(string desiredName) - => CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists); - public override IAsyncOperation CreateFileAsync(string desiredName, CreationCollisionOption options) - => CreateFileAsync(new MemoryStream(), desiredName, options); - - public override IAsyncOperation CreateFolderAsync(string desiredName) - => CreateFolderAsync(desiredName, CreationCollisionOption.FailIfExists); - public override IAsyncOperation CreateFolderAsync(string desiredName, CreationCollisionOption options) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - var zipDesiredName = System.IO.Path.Combine(Path, desiredName); - var item = await GetItemAsync(desiredName); - if (item is not null) - { - if (options != CreationCollisionOption.ReplaceExisting) - { - return null; - } - await item.DeleteAsync(); - } - - using (var ms = new MemoryStream()) - { - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for reading.")) - { - SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append }; - compressor.CustomParameters.Add("cu", "on"); - compressor.SetFormatFromExistingArchive(archiveStream); - var fileName = IO.Path.GetRelativePath(containerPath, zipDesiredName); - await compressor.CompressStreamDictionaryAsync(archiveStream, new Dictionary() { { fileName, null } }, Password, ms); - } - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for writing.")) - { - ms.Position = 0; - await ms.CopyToAsync(archiveStream); - await ms.FlushAsync(); - archiveStream.SetLength(archiveStream.Position); - } - } - - var folder = new ZipStorageFolder(zipDesiredName, containerPath, backingFile); - ((IPasswordProtectedItem)folder).CopyFrom(this); - return folder; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncOperation MoveAsync(IStorageFolder destinationFolder) => throw new NotSupportedException(); - public override IAsyncOperation MoveAsync(IStorageFolder destinationFolder, NameCollisionOption option) => throw new NotSupportedException(); - - public override IAsyncAction RenameAsync(string desiredName) => RenameAsync(desiredName, NameCollisionOption.FailIfExists); - public override IAsyncAction RenameAsync(string desiredName, NameCollisionOption option) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () => - { - if (Path == containerPath) - { - if (backingFile is not null) - { - await backingFile.RenameAsync(desiredName, option); - } - else - { - var parentPath = IO.Path.GetDirectoryName(Path) ?? throw new InvalidOperationException("The archive path has no parent."); - var fileName = IO.Path.Combine(parentPath, desiredName); - PInvoke.MoveFileFromApp(Path, fileName); - } - } - else - { - var index = await FetchZipIndex() - ?? throw new InvalidDataException($"The archive '{containerPath}' could not be read."); - if (index.IsEmpty()) - { - return; - } - using (var ms = new MemoryStream()) - { - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for reading.")) - { - SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append }; - compressor.CustomParameters.Add("cu", "on"); - compressor.SetFormatFromExistingArchive(archiveStream); - var folderKey = IO.Path.GetRelativePath(containerPath, Path); - var parentPath = IO.Path.GetDirectoryName(folderKey) - ?? throw new InvalidOperationException("The archive entry has no parent."); - var folderDes = IO.Path.Combine(parentPath, desiredName); - var entriesMap = new Dictionary(index.Select(x => new KeyValuePair(x.Index, - IO.Path.Combine(folderDes, IO.Path.GetRelativePath(folderKey, x.Key))))); - await compressor.ModifyArchiveAsync(archiveStream, entriesMap, Password, ms); - } - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for writing.")) - { - ms.Position = 0; - await ms.CopyToAsync(archiveStream); - await ms.FlushAsync(); - archiveStream.SetLength(archiveStream.Position); - } - } - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override IAsyncAction DeleteAsync() => DeleteAsync(StorageDeleteOption.Default); - public override IAsyncAction DeleteAsync(StorageDeleteOption option) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.WrapAsync(async () => - { - if (Path == containerPath) - { - if (backingFile is not null) - { - await backingFile.DeleteAsync(); - } - else if (option == StorageDeleteOption.PermanentDelete) - { - PInvoke.DeleteFileFromApp(Path); - } - else - { - throw new NotSupportedException("Moving to recycle bin is not supported."); - } - } - else - { - var index = await FetchZipIndex() - ?? throw new InvalidDataException($"The archive '{containerPath}' could not be read."); - if (index.IsEmpty()) - { - return; - } - using (var ms = new MemoryStream()) - { - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for reading.")) - { - SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append }; - compressor.CustomParameters.Add("cu", "on"); - compressor.SetFormatFromExistingArchive(archiveStream); - var entriesMap = new Dictionary(index.Select(x => new KeyValuePair(x.Index, null))); - await compressor.ModifyArchiveAsync(archiveStream, entriesMap, Password, ms); - } - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for writing.")) - { - ms.Position = 0; - await ms.CopyToAsync(archiveStream); - await ms.FlushAsync(); - archiveStream.SetLength(archiveStream.Position); - } - } - } - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - public override bool AreQueryOptionsSupported(QueryOptions queryOptions) => false; - public override bool IsCommonFileQuerySupported(CommonFileQuery query) => false; - public override bool IsCommonFolderQuerySupported(CommonFolderQuery query) => false; - - public override StorageItemQueryResult CreateItemQuery() => throw new NotSupportedException(); - public override BaseStorageItemQueryResult CreateItemQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override StorageFileQueryResult CreateFileQuery() => throw new NotSupportedException(); - public override StorageFileQueryResult CreateFileQuery(CommonFileQuery query) => throw new NotSupportedException(); - public override BaseStorageFileQueryResult CreateFileQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override StorageFolderQueryResult CreateFolderQuery() => throw new NotSupportedException(); - public override StorageFolderQueryResult CreateFolderQuery(CommonFolderQuery query) => throw new NotSupportedException(); - public override BaseStorageFolderQueryResult CreateFolderQueryWithOptions(QueryOptions queryOptions) => new(this, queryOptions); - - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (Path != containerPath) - { - return null; - } - var zipFile = await StorageFile.GetFileFromPathAsync(Path); - return await zipFile.GetThumbnailAsync(mode); - }); - } - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (Path != containerPath) - { - return null; - } - var zipFile = await StorageFile.GetFileFromPathAsync(Path); - return await zipFile.GetThumbnailAsync(mode, requestedSize); - }); - } - public override IAsyncOperation GetThumbnailAsync(ThumbnailMode mode, uint requestedSize, ThumbnailOptions options) - { - return AsyncInfo.Run(async (cancellationToken) => - { - if (Path != containerPath) - { - return null; - } - var zipFile = await StorageFile.GetFileFromPathAsync(Path); - return await zipFile.GetThumbnailAsync(mode, requestedSize, options); - }); - } - - private static bool CheckAccess(string path) - { - return SafetyExtensions.IgnoreExceptions(() => - { - var hFile = Win32Helper.OpenFileForRead(path); - if (hFile.IsInvalid) - { - return false; - } - using var stream = new FileStream(hFile, FileAccess.Read); - return CheckAccess(stream); - }); - } - private static bool CheckAccess(Stream stream) - { - try - { - using (SevenZipExtractor zipFile = new SevenZipExtractor(stream)) - { - //zipFile.IsStreamOwner = false; - return zipFile.ArchiveFileData is not null; - } - } - catch (SevenZipOpenFailedException ex) - { - return ex.Result == OperationResult.WrongPassword; - } - catch - { - return false; - } - } - private static async Task CheckAccess(BaseStorageFile file) - { - return await SafetyExtensions.IgnoreExceptions(async () => - { - using var stream = await file.OpenReadAsync() - ?? throw new IOException("The archive could not be opened for reading."); - return CheckAccess(stream.AsStream()); - }); - } - - public static Task InitArchive(string path, OutArchiveFormat format) - { - return SafetyExtensions.IgnoreExceptions(() => - { - var hFile = Win32Helper.OpenFileForRead(path, true); - if (hFile.IsInvalid) - { - return Task.FromResult(false); - } - using var stream = new FileStream(hFile, FileAccess.ReadWrite); - return InitArchive(stream, format); - }); - } - public static Task InitArchive(IStorageFile file, OutArchiveFormat format) - { - return SafetyExtensions.IgnoreExceptions(async () => - { - using var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); - await using var stream = fileStream.AsStream(); - return await InitArchive(stream, format); - }); - } - private static async Task InitArchive(Stream stream, OutArchiveFormat format) - { - stream.SetLength(0); - var compressor = new SevenZipCompressor() - { - CompressionMode = CompressionMode.Create, - ArchiveFormat = format - }; - compressor.CustomParameters.Add("cu", "on"); - await compressor.CompressStreamDictionaryAsync(stream, new Dictionary()); - await stream.FlushAsync(); - return true; - } - - public async Task ValidateCredentialsAsync() - { - try - { - using SevenZipExtractor? zipFile = await OpenZipFileAsync(); - return zipFile?.ArchiveFileData is not null; - } - catch (Exception) // SevenZipOpenFailedException(WrongPassword) for bad credentials; IO exceptions (e.g. archive deleted meanwhile) equally mean the credentials can't be verified - { - return false; - } - } - - private IAsyncOperation OpenZipFileAsync() - { - return AsyncInfo.Run(async (cancellationToken) => - { - var zipFile = await OpenZipFileAsync(FileAccessMode.Read); - return zipFile is not null ? new SevenZipExtractor(zipFile, Password) : null; - }); - } - - private IAsyncOperation OpenZipFileAsync(FileAccessMode accessMode) - { - return AsyncInfo.Run(async (cancellationToken) => - { - bool readWrite = accessMode is FileAccessMode.ReadWrite; - if (backingFile is not null) - { - var stream = await backingFile.OpenAsync(accessMode); - return stream?.AsStream(); - } - else - { - var hFile = Win32Helper.OpenFileForRead(containerPath, readWrite); - return hFile.IsInvalid ? null : new FileStream(hFile, readWrite ? FileAccess.ReadWrite : FileAccess.Read); - } - }); - } - - private async Task?> FetchZipIndex() - { - using (SevenZipExtractor? zipFile = await OpenZipFileAsync()) - { - if (zipFile is null || zipFile.ArchiveFileData is null) - { - return null; - } - //zipFile.IsStreamOwner = true; - return zipFile.GetArchiveFileData(containerPath).Where(x => System.IO.Path.Combine(containerPath, x.FileName).IsSubPathOf(Path)).Select(e => (e.Index, e.FileName)); - } - } - - public IAsyncOperation CreateFileAsync(Stream contents, string desiredName) - => CreateFileAsync(new MemoryStream(), desiredName, CreationCollisionOption.FailIfExists); - - public IAsyncOperation CreateFileAsync(Stream contents, string desiredName, CreationCollisionOption options) - { - return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () => - { - var zipDesiredName = System.IO.Path.Combine(Path, desiredName); - var item = await GetItemAsync(desiredName); - if (item is not null) - { - if (options != CreationCollisionOption.ReplaceExisting) - { - return null; - } - await item.DeleteAsync(); - } - - using (var ms = new MemoryStream()) - { - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.Read) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for reading.")) - { - SevenZipCompressor compressor = new SevenZipCompressor() { CompressionMode = CompressionMode.Append }; - compressor.CustomParameters.Add("cu", "on"); - compressor.SetFormatFromExistingArchive(archiveStream); - var fileName = IO.Path.GetRelativePath(containerPath, zipDesiredName); - await compressor.CompressStreamDictionaryAsync(archiveStream, new Dictionary() { { fileName, contents } }, Password, ms); - } - await using (var archiveStream = await OpenZipFileAsync(FileAccessMode.ReadWrite) - ?? throw new IOException($"The archive '{containerPath}' could not be opened for writing.")) - { - ms.Position = 0; - await ms.CopyToAsync(archiveStream); - await ms.FlushAsync(); - archiveStream.SetLength(archiveStream.Position); - } - } - - var file = new ZipStorageFile(zipDesiredName, containerPath, backingFile); - ((IPasswordProtectedItem)file).CopyFrom(this); - file.CurrentEncoding = CurrentEncoding; - return file; - }, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync)); - } - - private sealed partial class ZipFolderBasicProperties : BaseBasicProperties - { - private ArchiveFileInfo entry; - - public ZipFolderBasicProperties(ArchiveFileInfo entry) => this.entry = entry; - - public override DateTimeOffset DateModified => entry.LastWriteTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.LastWriteTime; - - public override DateTimeOffset DateCreated => entry.CreationTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.CreationTime; - - public override ulong Size => entry.Size; - } - - private sealed partial class ZipFolderBasicPropertiesWithEncoding : BaseBasicProperties - { - private ZipEntry entry; - - public ZipFolderBasicPropertiesWithEncoding(ZipEntry entry) => this.entry = entry; - - public override DateTimeOffset DateModified => entry.DateTime == DateTime.MinValue ? DateTimeOffset.MinValue : entry.DateTime; - - public override DateTimeOffset DateCreated => DateTimeOffset.MinValue; - - public override ulong Size => (ulong)entry.Size; - } - } -} diff --git a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.cs b/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.cs index 4c436547ddff..3469fba9bef9 100644 --- a/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.cs +++ b/src/Files.App/Utils/Storage/StorageItems/ZipStorageFolder.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.Platform.Abstractions.Archives; using Files.Shared.Helpers; using System.Collections.Concurrent; @@ -33,4 +32,3 @@ public abstract class ZipStorageFolder : BaseStorageFolder, IPasswordProtectedIt public IAsyncOperation CreateFileAsync(Stream contents, string name, CreationCollisionOption options) => Task.FromException(new NotSupportedException()).AsAsyncOperation(); } } -#endif diff --git a/src/Files.App/Utils/Taskbar/SystemTrayIcon.cs b/src/Files.App/Utils/Taskbar/SystemTrayIcon.cs deleted file mode 100644 index 315809b23da5..000000000000 --- a/src/Files.App/Utils/Taskbar/SystemTrayIcon.cs +++ /dev/null @@ -1,410 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.Extensions.Logging; -using Sentry; -using System.Drawing; -using System.Runtime.InteropServices; -using Windows.ApplicationModel; -using Windows.Foundation; -using Windows.System; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; - -namespace Files.App.Utils.Taskbar -{ - /// - /// Represents a tray icon of Notification Area so-called System Tray. - /// - public sealed partial class SystemTrayIcon : IDisposable - { - // Constants - - private const uint WM_FILES_UNIQUE_MESSAGE = 2048u; - private const uint WM_FILES_CONTEXTMENU_DOCSLINK = 1u; - private const uint WM_FILES_CONTEXTMENU_RESTART = 2u; - private const uint WM_FILES_CONTEXTMENU_QUIT = 3u; - - // Fields - - private readonly static Guid _trayIconGuid = AppLifecycleHelper.AppEnvironment switch - { - AppEnvironment.Dev => new Guid("684F2832-AC2B-4630-98C2-73D6AEBD4001"), - AppEnvironment.SideloadPreview => new Guid("684F2832-AC2B-4630-98C2-73D6AEBD4002"), - AppEnvironment.StorePreview => new Guid("684F2832-AC2B-4630-98C2-73D6AEBD4003"), - AppEnvironment.SideloadStable => new Guid("684F2832-AC2B-4630-98C2-73D6AEBD4004"), - AppEnvironment.StoreStable => new Guid("684F2832-AC2B-4630-98C2-73D6AEBD4005"), - _ => new Guid("684F2832-AC2B-4630-98C2-73D6AEBD4001") - }; - - - private readonly SystemTrayIconWindow _IconWindow; - - private readonly uint _taskbarRestartMessageId; - - private bool _notifyIconCreated; - - private DateTime _lastLaunchDate; - - // Properties - - public Guid Id { get; private set; } - - private bool _IsVisible; - public bool IsVisible - { - get - { - return _IsVisible; - } - private set - { - if (_IsVisible != value) - { - _IsVisible = value; - - if (!value) - DeleteNotifyIcon(); - else - CreateOrModifyNotifyIcon(); - } - } - } - - private string _Tooltip; - public string Tooltip - { - get - { - return _Tooltip; - } - set - { - if (_Tooltip != value) - { - _Tooltip = value; - - CreateOrModifyNotifyIcon(); - } - } - } - - private Icon _Icon; - public Icon Icon - { - get - { - return _Icon; - } - set - { - if (_Icon != value) - { - _Icon = value; - - CreateOrModifyNotifyIcon(); - } - } - } - - private Rect Position - { - get - { - if (!IsVisible) - return default; - - NOTIFYICONIDENTIFIER identifier = default; - identifier.cbSize = (uint)Marshal.SizeOf(); - identifier.hWnd = _IconWindow.WindowHandle; - identifier.guidItem = Id; - - // Get RECT - PInvoke.Shell_NotifyIconGetRect(in identifier, out RECT _IconLocation); - - return new Rect( - _IconLocation.left, - _IconLocation.top, - _IconLocation.right - _IconLocation.left, - _IconLocation.bottom - _IconLocation.top); - } - } - - // Constructor - - /// - /// Initializes an instance of . - /// - /// - /// Note that initializing an instance won't make the icon visible. - /// - public SystemTrayIcon() - { - _Icon = new(AppLifecycleHelper.AppIconPath); - _Tooltip = Package.Current.DisplayName; - _taskbarRestartMessageId = PInvoke.RegisterWindowMessage("TaskbarCreated"); - - Id = _trayIconGuid; - _IconWindow = new SystemTrayIconWindow(this); - - CreateOrModifyNotifyIcon(); - } - - // Public Methods - - /// - /// Shows the tray icon. - /// - public SystemTrayIcon Show() - { - IsVisible = true; - - return this; - } - - /// - /// Hides the tray icon. - /// - public SystemTrayIcon Hide() - { - IsVisible = false; - - return this; - } - - /// - /// Re-adds the notify icon if the shell no longer has it, e.g. after a sibling instance - /// sharing the same GUID deleted it on exit. No-op when hidden or still registered. - /// - public void EnsureCreated() - { - if (!IsVisible) - return; - - NOTIFYICONIDENTIFIER identifier = default; - identifier.cbSize = (uint)Marshal.SizeOf(); - identifier.guidItem = Id; - - // Icon is still registered with the shell - if (PInvoke.Shell_NotifyIconGetRect(in identifier, out _).Succeeded) - return; - - _notifyIconCreated = false; - CreateOrModifyNotifyIcon(); - } - - // Private Methods - - private void CreateOrModifyNotifyIcon() - { - if (IsVisible) - { - NOTIFYICONDATAW lpData = default; - - lpData.cbSize = (uint)Marshal.SizeOf(); - lpData.hWnd = _IconWindow.WindowHandle; - lpData.uCallbackMessage = WM_FILES_UNIQUE_MESSAGE; - lpData.hIcon = (Icon != null) ? new HICON(Icon.Handle) : default; - lpData.guidItem = Id; - lpData.uFlags = NOTIFY_ICON_DATA_FLAGS.NIF_MESSAGE | NOTIFY_ICON_DATA_FLAGS.NIF_ICON | NOTIFY_ICON_DATA_FLAGS.NIF_TIP | NOTIFY_ICON_DATA_FLAGS.NIF_GUID | NOTIFY_ICON_DATA_FLAGS.NIF_SHOWTIP; - lpData.szTip = _Tooltip ?? string.Empty; - - if (!_notifyIconCreated) - { - // Delete the existing icon - PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_DELETE, in lpData); - - _notifyIconCreated = true; - - // Add a new icon - PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_ADD, in lpData); - - lpData.Anonymous.uVersion = 4u; - - // Set the icon handler version - // NOTE: Do not omit this code. If you remove, the icon won't be shown. - PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_SETVERSION, in lpData); - } - else - { - // Modify the existing icon - PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_MODIFY, in lpData); - } - } - } - - private void DeleteNotifyIcon() - { - if (_notifyIconCreated) - { - _notifyIconCreated = false; - - NOTIFYICONDATAW lpData = default; - - lpData.cbSize = (uint)Marshal.SizeOf(); - lpData.hWnd = _IconWindow.WindowHandle; - lpData.guidItem = Id; - lpData.uFlags = NOTIFY_ICON_DATA_FLAGS.NIF_MESSAGE | NOTIFY_ICON_DATA_FLAGS.NIF_ICON | NOTIFY_ICON_DATA_FLAGS.NIF_TIP | NOTIFY_ICON_DATA_FLAGS.NIF_GUID | NOTIFY_ICON_DATA_FLAGS.NIF_SHOWTIP; - - // Delete the existing icon - PInvoke.Shell_NotifyIcon(NOTIFY_ICON_MESSAGE.NIM_DELETE, in lpData); - } - } - - private void ShowContextMenu() - { - PInvoke.GetCursorPos(out var lpPoint); - - DestroyMenuSafeHandle hMenu = PInvoke.CreatePopupMenu_SafeHandle(); - - // Generate the classic context menu - PInvoke.AppendMenu(hMenu, MENU_ITEM_FLAGS.MF_BYCOMMAND, WM_FILES_CONTEXTMENU_DOCSLINK, Strings.Documentation.GetLocalizedResource()); - PInvoke.AppendMenu(hMenu, MENU_ITEM_FLAGS.MF_SEPARATOR, 0u, string.Empty); - //PInvoke.AppendMenu(hMenu, MENU_ITEM_FLAGS.MF_BYCOMMAND, WM_FILES_CONTEXTMENU_RESTART, "Restart".GetLocalizedResource()); - PInvoke.AppendMenu(hMenu, MENU_ITEM_FLAGS.MF_BYCOMMAND, WM_FILES_CONTEXTMENU_QUIT, Strings.Quit.GetLocalizedResource()); - PInvoke.SetForegroundWindow(_IconWindow.WindowHandle); - - TRACK_POPUP_MENU_FLAGS tRACK_POPUP_MENU_FLAGS = - TRACK_POPUP_MENU_FLAGS.TPM_RETURNCMD | - (PInvoke.GetSystemMetricsForDpi(SYSTEM_METRICS_INDEX.SM_MENUDROPALIGNMENT, PInvoke.GetDpiForWindow(_IconWindow.WindowHandle)) != 0 - ? TRACK_POPUP_MENU_FLAGS.TPM_RIGHTALIGN - : TRACK_POPUP_MENU_FLAGS.TPM_LEFTBUTTON); - - switch (PInvoke.TrackPopupMenuEx(hMenu, (uint)tRACK_POPUP_MENU_FLAGS, lpPoint.X, lpPoint.Y, _IconWindow.WindowHandle, null).Value) - { - case 1: - OnDocumentationClicked(); - break; - case 2: - OnRestartClicked(); - break; - case 3: - OnQuitClicked(); - break; - } - } - - private void OnLeftClicked() - { - // Prevents duplicate launch - if (DateTime.Now - _lastLaunchDate < TimeSpan.FromSeconds(1)) - return; - - if (Program.Pool is not null) - { - _lastLaunchDate = DateTime.Now; - - _ = Launcher.LaunchUriAsync(new Uri("files-dev:")); - } - else - MainWindow.Instance.Activate(); - } - - private void OnDocumentationClicked() - { - Launcher.LaunchUriAsync(new Uri(Constants.ExternalUrl.DocumentationUrl)).AsTask(); - } - - private void OnRestartClicked() - { - Microsoft.Windows.AppLifecycle.AppInstance.Restart(""); - - var pool = new Semaphore(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance", out var isNew); - if (!isNew) - pool.Release(); - - Environment.Exit(0); - } - - private void OnQuitClicked() - { - try - { - Hide(); - - App.AppModel.ForceProcessTermination = true; - - var pool = new Semaphore(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance", out var isNew); - if (!isNew) - pool.Release(); - else - App.Current.Exit(); - } - catch (Exception ex) - { - SentrySdk.CaptureException(ex, scope => - { - scope.Level = SentryLevel.Fatal; - scope.SetTag("location", "SystemTrayIcon.OnQuitClicked"); - scope.SetExtra("AppModelIsNull", App.AppModel is null); - scope.SetExtra("AppCurrentIsNull", App.Current is null); - scope.SetExtra("ProgramPoolIsNull", Program.Pool is null); - }); - - // The user requested quit; force termination as a last resort - Environment.Exit(0); - } - } - - internal LRESULT WindowProc(HWND hWnd, uint uMsg, WPARAM wParam, LPARAM lParam) - { - try - { - switch (uMsg) - { - case WM_FILES_UNIQUE_MESSAGE: - { - switch ((uint)(lParam.Value & 0xFFFF)) - { - case PInvoke.WM_LBUTTONUP: - { - PInvoke.SetForegroundWindow(hWnd); - OnLeftClicked(); - - break; - } - case PInvoke.WM_RBUTTONUP: - { - ShowContextMenu(); - - break; - } - } - - break; - } - case PInvoke.WM_DESTROY: - { - DeleteNotifyIcon(); - - break; - } - default: - { - if (uMsg == _taskbarRestartMessageId) - { - DeleteNotifyIcon(); - CreateOrModifyNotifyIcon(); - } - - return PInvoke.DefWindowProc(hWnd, uMsg, wParam, lParam); - } - } - } - catch (Exception ex) - { - // A managed exception escaping this native message-pump callback would crash the process. - App.Logger?.LogWarning(ex, "Unhandled exception in the system tray WindowProc."); - } - - return default; - } - - public void Dispose() - { - _IconWindow.Dispose(); - } - } -} diff --git a/src/Files.App/Utils/Taskbar/SystemTrayIconWindow.cs b/src/Files.App/Utils/Taskbar/SystemTrayIconWindow.cs deleted file mode 100644 index 8a44bbc84911..000000000000 --- a/src/Files.App/Utils/Taskbar/SystemTrayIconWindow.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Runtime.InteropServices; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.UI.WindowsAndMessaging; -using WNDPROC = Windows.Win32.Extras.ManagedWNDPROC; - -namespace Files.App.Utils.Taskbar -{ - /// - /// Represents an icon window of Notification Area so-called System Tray. - ///
- /// This is provided to handle context menu and retrieve mouse events, not a regular window class. - ///
- public sealed partial class SystemTrayIconWindow : IDisposable - { - private SystemTrayIcon? _trayIcon; - - private readonly WNDPROC _windowProcedure; - - private HWND _windowHandle; - internal HWND WindowHandle - => _windowHandle; - - public unsafe SystemTrayIconWindow(SystemTrayIcon icon) - { - _windowProcedure = WindowProc; - _trayIcon = icon; - string text = "FilesTrayIcon_" + _trayIcon.Id; - - fixed (char* ptr = text) - { - var pWindProc = Marshal.GetFunctionPointerForDelegate(_windowProcedure); - var pfnWndProc = (delegate* unmanaged[Stdcall])pWindProc; - - WNDCLASSEXW param = new() - { - cbSize = (uint)Marshal.SizeOf(), - style = WNDCLASS_STYLES.CS_DBLCLKS, - lpfnWndProc = pfnWndProc, - cbClsExtra = 0, - cbWndExtra = 0, - hInstance = PInvoke.GetModuleHandle(default(PCWSTR)), - lpszClassName = ptr - }; - - PInvoke.RegisterClassEx(in param); - } - - _windowHandle = PInvoke.CreateWindowEx( - WINDOW_EX_STYLE.WS_EX_LEFT, - text, - string.Empty, - WINDOW_STYLE.WS_OVERLAPPED, - 0, - 0, - 1, - 1, - default, - null, - null, - null); - - if (_windowHandle == default) - throw new Win32Exception("ERR: Message window handle was not a valid pointer."); - } - - private LRESULT WindowProc(HWND hWnd, uint uMsg, WPARAM wParam, LPARAM lParam) - { - return _trayIcon!.WindowProc(hWnd, uMsg, wParam, lParam); - } - - public void Dispose() - { - if (_windowHandle != default) - { - PInvoke.DestroyWindow(_windowHandle); - _windowHandle = default; - } - - _trayIcon = null; - } - } -} diff --git a/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.Windows.cs b/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.Windows.cs deleted file mode 100644 index 1e649cc1744b..000000000000 --- a/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.Windows.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using System.IO; -using System.Runtime.InteropServices; -using System.Windows.Input; -using Windows.Win32; -using Windows.Win32.UI.Shell; - -namespace Files.App.ViewModels.Dialogs -{ - public sealed partial class CreateShortcutDialogViewModel : ObservableObject - { - private unsafe Task SelectDestination() - { - BROWSEINFOW bi = new() - { - ulFlags = 0x00004000 - }; - - Span displayName = stackalloc char[260]; - fixed (char* displayNameBuffer = displayName) - fixed (char* title = "Select a folder") - { - bi.pszDisplayName = displayNameBuffer; - bi.lpszTitle = title; - var pidl = PInvoke.SHBrowseForFolder(in bi); - if (pidl is not null) - { - Span path = stackalloc char[260]; - fixed (char* pathBuffer = path) - { - if (PInvoke.SHGetPathFromIDList(pidl, pathBuffer)) - { - var length = path.IndexOf('\0'); - ShortcutTarget = path[..(length < 0 ? path.Length : length)].ToString(); - } - } - - Marshal.FreeCoTaskMem((nint)pidl); - } - } - - return Task.CompletedTask; - } - - private async Task CreateShortcutAsync() - { - var extension = DestinationPathExists ? ".lnk" : ".url"; - - var shortcutName = FilesystemHelpers.GetShortcutNamingPreference(_shortcutName); - ShortcutCompleteName = shortcutName + extension; - var filePath = Path.Combine(WorkingDirectory, ShortcutCompleteName); - - int fileNumber = 1; - while (Path.Exists(filePath)) - { - ShortcutCompleteName = shortcutName + $" ({++fileNumber})" + extension; - filePath = Path.Combine(WorkingDirectory, ShortcutCompleteName); - } - - ShortcutCreatedSuccessfully = await FileOperationsHelpers.CreateOrUpdateLinkAsync(filePath, FullPath, Arguments); - } - } -} diff --git a/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.cs b/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.cs index 8295ea38a65a..f22f1f21426e 100644 --- a/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.cs +++ b/src/Files.App/ViewModels/Dialogs/CreateShortcutDialogViewModel.cs @@ -227,16 +227,12 @@ private bool IsValidAbsolutePath(string path) return Path.Exists(path) && Path.IsPathFullyQualified(path) && path != Path.GetPathRoot(path); } -#if !WINDOWS // LINUX-TODO(shortcuts): native shortcut creation is hidden on Linux. private Task SelectDestination() => Task.CompletedTask; -#endif -#if !WINDOWS private Task CreateShortcutAsync() => Task.CompletedTask; -#endif private void AutoFillName() { diff --git a/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.Windows.cs b/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.Windows.cs deleted file mode 100644 index 92938188c57a..000000000000 --- a/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.Windows.cs +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using System.Text; -using System.Windows.Input; -using Windows.Storage; - -namespace Files.App.ViewModels.Dialogs -{ - public sealed partial class DecompressArchiveDialogViewModel : ObservableObject - { - // Services - private ICommonDialogService CommonDialogService { get; } = Ioc.Default.GetRequiredService(); - private readonly IUserSettingsService UserSettingsService = Ioc.Default.GetRequiredService(); - - // Fields - private readonly IStorageFile archive; - - // Properties - public BaseStorageFolder? DestinationFolder { get; private set; } - - private string destinationFolderPath; - public string DestinationFolderPath - { - get => destinationFolderPath; - set - { - if (SetProperty(ref destinationFolderPath, value)) - { - OnPropertyChanged(nameof(IsDestinationPathValid)); - } - } - } - - public bool IsDestinationPathValid - { - get - { - try - { - if (string.IsNullOrWhiteSpace(DestinationFolderPath)) - return false; - - string? parentDir = Path.GetDirectoryName(DestinationFolderPath); - string finalSegment = Path.GetFileName(DestinationFolderPath); - - // Check parent directory exists - if (string.IsNullOrWhiteSpace(parentDir) || !Directory.Exists(parentDir)) - return false; - - // Check for invalid characters (IsValidForFilename already does this) - if (!FilesystemHelpers.IsValidForFilename(finalSegment)) - return false; - - return true; - } - catch - { - // Catch any exception to prevent crashes - return false; - } - } - } - - private bool openDestinationFolderOnCompletion; - public bool OpenDestinationFolderOnCompletion - { - get => openDestinationFolderOnCompletion; - set => SetProperty(ref openDestinationFolderOnCompletion, value); - } - - private bool isArchiveEncrypted; - public bool IsArchiveEncrypted - { - get => isArchiveEncrypted; - set => SetProperty(ref isArchiveEncrypted, value); - } - - private bool isArchiveEncodingUndetermined; - public bool IsArchiveEncodingUndetermined - { - get => isArchiveEncodingUndetermined; - set => SetProperty(ref isArchiveEncodingUndetermined, value); - } - - private Encoding? detectedEncoding; - public Encoding? DetectedEncoding - { - get => detectedEncoding; - set - { - SetProperty(ref detectedEncoding, value); - RefreshEncodingOptions(); - } - } - - private bool showPathSelection; - public bool ShowPathSelection - { - get => showPathSelection; - set => SetProperty(ref showPathSelection, value); - } - - public DisposableArray? Password { get; private set; } - - public EncodingItem[] EncodingOptions { get; set; } = EncodingItem.Defaults; - - public EncodingItem SelectedEncoding { get; set; } - - public ObservableCollection PreviousExtractionLocations { get; } = []; - - // Commands - public IRelayCommand PrimaryButtonClickCommand { get; private set; } - public ICommand SelectDestinationCommand { get; private set; } - public ICommand? QuerySubmittedCommand { get; private set; } - - // Constructor - public DecompressArchiveDialogViewModel(IStorageFile archive) - { - this.archive = archive; - destinationFolderPath = DefaultDestinationFolderPath(); - SelectedEncoding = EncodingOptions[0]; - - // Create commands - SelectDestinationCommand = new AsyncRelayCommand(SelectDestinationAsync); - PrimaryButtonClickCommand = new RelayCommand(password => Password = password); - } - - // Private Methods - private string DefaultDestinationFolderPath() - { - var directory = Path.GetDirectoryName(archive.Path); -#if HAS_UNO - var fileName = Ioc.Default.GetRequiredService().GetDefaultExtractFolderName(archive.Path); -#else - var fileName = Path.GetFileNameWithoutExtension(archive.Path); -#endif - return string.IsNullOrEmpty(directory) ? fileName : Path.Combine(directory, fileName); - } - - private async Task SelectDestinationAsync() - { - bool result = CommonDialogService.Open_FileOpenDialog(MainWindow.Instance.WindowHandle, true, [], Environment.SpecialFolder.Desktop, out var filePath); - if (!result) - return; - - DestinationFolder = await StorageHelpers.ToStorageItem(filePath); - DestinationFolderPath = (DestinationFolder is not null) ? DestinationFolder.Path : DefaultDestinationFolderPath(); - } - - private void RefreshEncodingOptions() - { - if (detectedEncoding != null) - { - EncodingOptions = EncodingItem.Defaults - .Prepend(new EncodingItem( - detectedEncoding, - string.Format(Strings.EncodingDetected.GetLocalizedResource(), detectedEncoding.EncodingName) - )) - .ToArray(); - } - else - { - EncodingOptions = EncodingItem.Defaults; - } - SelectedEncoding = EncodingOptions[0]; - } - - // Public Methods - public void UpdateSuggestions(string query) - { - var allItems = UserSettingsService.GeneralSettingsService.PreviousArchiveExtractionLocations; - if (allItems is null) - return; - - var filtered = allItems - .Where(item => item.StartsWith(query, StringComparison.OrdinalIgnoreCase)) - .ToList(); - - // Only update if results changed to prevent flickering - if (!filtered.SequenceEqual(PreviousExtractionLocations)) - { - PreviousExtractionLocations.Clear(); - foreach (var item in filtered) - PreviousExtractionLocations.Add(item); - } - } - } -} diff --git a/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.cs b/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.cs index 2141b5a1a12c..b1c508df0b1f 100644 --- a/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.cs +++ b/src/Files.App/ViewModels/Dialogs/DecompressArchiveDialogViewModel.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using System.IO; using System.Text; using System.Windows.Input; @@ -183,4 +182,3 @@ public void UpdateSuggestions(string query) } } -#endif diff --git a/src/Files.App/ViewModels/Properties/BasePropertiesPage.cs b/src/Files.App/ViewModels/Properties/BasePropertiesPage.cs index 7f6c8b270d6a..41d1dbddffc8 100644 --- a/src/Files.App/ViewModels/Properties/BasePropertiesPage.cs +++ b/src/Files.App/ViewModels/Properties/BasePropertiesPage.cs @@ -57,19 +57,6 @@ protected override void OnNavigatedTo(NavigationEventArgs e) ViewModel.FormatVisibility = false; } -#if WINDOWS - ViewModel.CleanupDriveCommand = new AsyncRelayCommand(() => StorageSenseHelper.OpenStorageSenseAsync(drivePath)); - ViewModel.FormatDriveCommand = new RelayCommand(async () => - { - try - { - await Win32Helper.OpenFormatDriveDialog(drivePath); - } - catch (Exception) - { - } - }); -#endif } // Storage objects (multi-selected) else if (np.Parameter is List items) diff --git a/src/Files.App/ViewModels/Properties/CompatibilityViewModel.Windows.cs b/src/Files.App/ViewModels/Properties/CompatibilityViewModel.Windows.cs deleted file mode 100644 index 069fc89d34c5..000000000000 --- a/src/Files.App/ViewModels/Properties/CompatibilityViewModel.Windows.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.Windows.Input; - -namespace Files.App.ViewModels.Properties -{ - /// - /// Represents view model of . - /// - public sealed partial class CompatibilityViewModel : ObservableObject - { - // Dependency injections - - private IWindowsCompatibilityService WindowsCompatibilityService { get; } = Ioc.Default.GetRequiredService(); - - // Properties - - public string ItemPath { get; } - - public WindowsCompatibilityOptions CompatibilityOptions { get; } - - public Dictionary CompatibilityModes { get; } = []; - public Dictionary ReducedColorModes { get; } = []; - public Dictionary HighDpiOptions { get; } = []; - public Dictionary HighDpiOverrides { get; } = []; - - public string SelectedCompatibilityMode - { - get => CompatibilityModes.GetValueOrDefault(CompatibilityOptions.CompatibilityMode)!; - set => SetProperty(ref CompatibilityOptions.CompatibilityMode, CompatibilityModes.First(e => e.Value == value).Key); - } - - public string SelectedReducedColorMode - { - get => ReducedColorModes.GetValueOrDefault(CompatibilityOptions.ReducedColorMode)!; - set => SetProperty(ref CompatibilityOptions.ReducedColorMode, ReducedColorModes.First(e => e.Value == value).Key); - } - - public bool RunIn40x480Resolution - { - get => CompatibilityOptions.RunIn40x480Resolution; - set => SetProperty(ref CompatibilityOptions.RunIn40x480Resolution, value); - } - - public bool DisableFullscreenOptimization - { - get => CompatibilityOptions.DisableFullscreenOptimization; - set => SetProperty(ref CompatibilityOptions.DisableFullscreenOptimization, value); - } - - public bool RunAsAdministrator - { - get => CompatibilityOptions.RunAsAdministrator; - set => SetProperty(ref CompatibilityOptions.RunAsAdministrator, value); - } - - public bool RegisterForRestart - { - get => CompatibilityOptions.RegisterForRestart; - set => SetProperty(ref CompatibilityOptions.RegisterForRestart, value); - } - - public string SelectedHighDpiOption - { - get => HighDpiOptions.GetValueOrDefault(CompatibilityOptions.HighDpiOption)!; - set => SetProperty(ref CompatibilityOptions.HighDpiOption, HighDpiOptions.First(e => e.Value == value).Key); - } - - public string SelectedHighDpiOverride - { - get => HighDpiOverrides.GetValueOrDefault(CompatibilityOptions.HighDpiOverride)!; - set => SetProperty(ref CompatibilityOptions.HighDpiOverride, HighDpiOverrides.First(e => e.Value == value).Key); - } - - // Commands - - public ICommand RunTroubleshooterCommand { get; set; } - - // Constructor - - public CompatibilityViewModel(ListedItem item) - { - var targetPath = (item as IShortcutItem)?.TargetPath; - ItemPath = (!string.IsNullOrEmpty(targetPath) ? targetPath : item.ItemPath) - ?? throw new InvalidOperationException("The selected item does not have a compatibility target path."); - - CompatibilityOptions = WindowsCompatibilityService.GetCompatibilityOptionsForPath(ItemPath); - - CompatibilityModes.Add(WindowsCompatModeKind.None, Strings.None.GetLocalizedResource()); - CompatibilityModes.Add(WindowsCompatModeKind.WindowsVista, "Windows Vista"); - CompatibilityModes.Add(WindowsCompatModeKind.WindowsVistaSP1, "Windows Vista (Service Pack 1)"); - CompatibilityModes.Add(WindowsCompatModeKind.WindowsVistaSP2, "Windows Vista (Service Pack 2)"); - CompatibilityModes.Add(WindowsCompatModeKind.Windows7, "Windows 7"); - CompatibilityModes.Add(WindowsCompatModeKind.Windows8, "Windows 8"); - - ReducedColorModes.Add(WindowsCompatReducedColorModeKind.None, Strings.CompatibilityNoReducedColor.GetLocalizedResource()); - ReducedColorModes.Add(WindowsCompatReducedColorModeKind.Color8Bit, Strings.CompatibilityReducedColorModeColor8bit.GetLocalizedResource()); - ReducedColorModes.Add(WindowsCompatReducedColorModeKind.Color16Bit, Strings.CompatibilityReducedColorModeColor16bit.GetLocalizedResource()); - - HighDpiOptions.Add(WindowsCompatDPIOptionKind.None, Strings.CompatibilityDoNotAdjustDPI.GetLocalizedResource()); - HighDpiOptions.Add(WindowsCompatDPIOptionKind.UseDPIOnLogin, Strings.CompatibilityOnWindowsLogin.GetLocalizedResource()); - HighDpiOptions.Add(WindowsCompatDPIOptionKind.UseDPIOnProgramStart, Strings.CompatibilityOnProgramStart.GetLocalizedResource()); - - HighDpiOverrides.Add(WindowsCompatDpiOverrideKind.None, Strings.CompatibilityDoNotOverrideDPI.GetLocalizedResource()); - HighDpiOverrides.Add(WindowsCompatDpiOverrideKind.Advanced, Strings.Advanced.GetLocalizedResource()); - HighDpiOverrides.Add(WindowsCompatDpiOverrideKind.Application, Strings.Application.GetLocalizedResource()); - HighDpiOverrides.Add(WindowsCompatDpiOverrideKind.System, Strings.System.GetLocalizedResource()); - HighDpiOverrides.Add(WindowsCompatDpiOverrideKind.SystemAdvanced, Strings.CompatibilitySystemEnhanced.GetLocalizedResource()); - - RunTroubleshooterCommand = new AsyncRelayCommand(ExecuteRunTroubleshooterCommand); - } - - // Methods - - public bool SetCompatibilityOptions() - { - return WindowsCompatibilityService.SetCompatibilityOptionsForPath(ItemPath, CompatibilityOptions); - } - - private Task ExecuteRunTroubleshooterCommand() - { - return LaunchHelper.RunCompatibilityTroubleshooterAsync(ItemPath); - } - } -} diff --git a/src/Files.App/ViewModels/Properties/CustomizationViewModel.Windows.cs b/src/Files.App/ViewModels/Properties/CustomizationViewModel.Windows.cs deleted file mode 100644 index 3d83042b5a4e..000000000000 --- a/src/Files.App/ViewModels/Properties/CustomizationViewModel.Windows.cs +++ /dev/null @@ -1,198 +0,0 @@ -using Files.Shared.Helpers; -using Microsoft.UI.Windowing; -using Microsoft.UI.Xaml.Controls; -using System.IO; -using System.Windows.Input; - -namespace Files.App.ViewModels.Properties -{ - public sealed partial class CustomizationViewModel : ObservableObject - { - private ICommonDialogService CommonDialogService { get; } = Ioc.Default.GetRequiredService(); - - private static string DefaultIconDllFilePath - => Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "SHELL32.dll"); - - private readonly AppWindow? _appWindow; - - private readonly IShellPage? _appInstance; - - private readonly string? _selectedItemPath; - - private bool _isIconChanged; - - public readonly bool IsShortcut; - - public ObservableCollection DllIcons { get; } = []; - - private string? _IconResourceItemPath; - public string? IconResourceItemPath - { - get => _IconResourceItemPath; - set - { - if (SetProperty(ref _IconResourceItemPath, value)) - { - DllIcons.Clear(); - - if (IsConvertibleImagePath(_IconResourceItemPath)) - { - ConvertImageInfoBarSeverity = InfoBarSeverity.Informational; - ConvertImageInfoBarMessage = Strings.ConvertToIconRequiredMessage.GetLocalizedResource(); - IsConvertImageInfoBarOpen = true; - return; - } - - IsConvertImageInfoBarOpen = false; - - if (Path.Exists(_IconResourceItemPath)) - { - var icons = Win32Helper.ExtractIconsFromDLL(_IconResourceItemPath); - if (icons?.Count is null or 0) - return; - - foreach (var item in icons) - DllIcons.Add(item); - } - } - } - } - - private IconFileInfo? _SelectedDllIcon; - public IconFileInfo? SelectedDllIcon - { - get => _SelectedDllIcon; - set - { - if (SetProperty(ref _SelectedDllIcon, value)) - _isIconChanged = true; - } - } - - [ObservableProperty] public partial bool IsConvertImageInfoBarOpen { get; set; } - [ObservableProperty] public partial InfoBarSeverity ConvertImageInfoBarSeverity { get; set; } - [ObservableProperty] public partial string? ConvertImageInfoBarMessage { get; set; } - - public ICommand? RestoreDefaultIconCommand { get; private set; } - public ICommand? OpenFilePickerCommand { get; private set; } - public ICommand? ConvertImageToIconCommand { get; private set; } - - public CustomizationViewModel(IShellPage appInstance, BaseProperties baseProperties, AppWindow appWindow) - { - ListedItem? item; - if (baseProperties is FileProperties fileProperties) - item = fileProperties.Item; - else if (baseProperties is FolderProperties folderProperties) - item = folderProperties.Item; - else - return; - - _appInstance = appInstance; - _appWindow = appWindow; - IconResourceItemPath = DefaultIconDllFilePath; - IsShortcut = item.IsShortcut; - _selectedItemPath = item.ItemPath; - - - RestoreDefaultIconCommand = new RelayCommand(ExecuteRestoreDefaultIconCommand); - OpenFilePickerCommand = new RelayCommand(ExecuteOpenFilePickerCommand); - ConvertImageToIconCommand = new AsyncRelayCommand(ExecuteConvertImageToIconCommandAsync); - } - - private static bool IsConvertibleImagePath(string? path) - { - return FileExtensionHelpers.IsConvertibleToIcoFile(path) && File.Exists(path); - } - - private void ExecuteRestoreDefaultIconCommand() - { - SelectedDllIcon = null; - _isIconChanged = true; - } - - private void ExecuteOpenFilePickerCommand() - { - var parentWindowId = (_appWindow - ?? throw new InvalidOperationException("The customization window has not been initialized.")).Id; - var hWnd = Microsoft.UI.Win32Interop.GetWindowFromWindowId(parentWindowId); - - string[] extensions = - [ - Strings.AllSupportedFiles.GetLocalizedResource(), "*.dll;*.exe;*.ico;*.icl;*.png;*.bmp;*.jpg;*.jpeg;*.jfif", - Strings.IconFiles.GetLocalizedResource(), "*.dll;*.exe;*.ico;*.icl", - Strings.ApplicationExtension.GetLocalizedResource(), "*.dll", - Strings.Application.GetLocalizedResource(), "*.exe", - Strings.IcoFileCapitalized.GetLocalizedResource(), "*.ico", - Strings.IclFileCapitalized.GetLocalizedResource(), "*.icl ", - Strings.ImageFiles.GetLocalizedResource(), "*.png;*.bmp;*.jpg;*.jpeg;*.jfif", - ]; - - var result = CommonDialogService.Open_FileOpenDialog(hWnd, false, extensions, Environment.SpecialFolder.MyComputer, out var filePath); - if (result) - IconResourceItemPath = filePath; - } - - private async Task ExecuteConvertImageToIconCommandAsync() - { - var imagePath = IconResourceItemPath; - if (imagePath is null || !IsConvertibleImagePath(imagePath)) - return; - - var appWindow = _appWindow - ?? throw new InvalidOperationException("The customization window has not been initialized."); - var hWnd = Microsoft.UI.Win32Interop.GetWindowFromWindowId(appWindow.Id); - if (!CommonDialogService.Open_FileSaveDialog(hWnd, false, [Strings.IcoFileCapitalized.GetLocalizedResource(), "*.ico"], Environment.SpecialFolder.MyPictures, out var icoFilePath)) - return; - - // The save dialog doesn't enforce an extension, and the shell only accepts real .ico files here - if (!Path.GetExtension(icoFilePath).Equals(".ico", StringComparison.OrdinalIgnoreCase)) - icoFilePath += ".ico"; - - var converted = await Task.Run(() => Win32Helper.ConvertImageToIcoFile(imagePath, icoFilePath)); - if (converted) - { - IconResourceItemPath = icoFilePath; - SelectedDllIcon = DllIcons.FirstOrDefault(); - } - else - { - ConvertImageInfoBarSeverity = InfoBarSeverity.Error; - ConvertImageInfoBarMessage = Strings.ConvertToIconError.GetLocalizedResource(); - IsConvertImageInfoBarOpen = true; - } - } - - public async Task UpdateIcon() - { - if (!_isIconChanged) - return false; - - var selectedItemPath = _selectedItemPath - ?? throw new InvalidOperationException("The selected item path has not been initialized."); - bool result = false; - - if (SelectedDllIcon is null) - { - result = IsShortcut - ? Win32Helper.SetCustomFileIcon(selectedItemPath, null) - : Win32Helper.SetCustomDirectoryIcon(selectedItemPath, null); - } - else - { - result = IsShortcut - ? Win32Helper.SetCustomFileIcon(selectedItemPath, IconResourceItemPath, SelectedDllIcon.Index) - : Win32Helper.SetCustomDirectoryIcon(selectedItemPath, IconResourceItemPath, SelectedDllIcon.Index); - } - - if (!result) - return false; - - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => - { - _appInstance?.ShellViewModel?.RefreshItems(null); - }); - - return true; - } - } -} diff --git a/src/Files.App/ViewModels/Properties/Items/BaseProperties.Windows.cs b/src/Files.App/ViewModels/Properties/Items/BaseProperties.Windows.cs deleted file mode 100644 index 19efa57b0d1a..000000000000 --- a/src/Files.App/ViewModels/Properties/Items/BaseProperties.Windows.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using System.IO; -using Microsoft.UI.Dispatching; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; -using FileAttributes = System.IO.FileAttributes; - -namespace Files.App.ViewModels.Properties -{ - public abstract partial class BaseProperties - { - private static unsafe (FindCloseSafeHandle Handle, WIN32_FIND_DATAW Data) FindFirstFile(string path) - { - WIN32_FIND_DATAW findData = default; - FindCloseSafeHandle hFile = PInvoke.FindFirstFileEx( - path, - FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - - return (hFile, findData); - } - - private async Task<(long size, long sizeOnDisk)> CalculateFolderSizeWindowsAsync(string path, CancellationToken token) - { - if (string.IsNullOrEmpty(path)) - { - // In MTP devices calculating folder size would be too slow - // Also should use StorageFolder methods instead of FindFirstFileEx - return (0, 0); - } - - long size = 0; - long sizeOnDisk = 0; - var (hFile, findData) = FindFirstFile(path + "\\*.*"); - using FindCloseSafeHandle findHandleScope = hFile; - - var count = 0; - if (!hFile.IsInvalid) - { - do - { - string fileName = findData.cFileName.ToString(); - if (((FileAttributes)findData.dwFileAttributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) - // Skip symbolic links and junctions - continue; - - if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory) - { - size += findData.GetSize(); - var fileSizeOnDisk = Win32Helper.GetFileSizeOnDisk(Path.Combine(path, fileName)); - sizeOnDisk += fileSizeOnDisk ?? 0; - ++count; - ViewModel.FilesCount++; - } - else if (fileName != "." && fileName != "..") - { - var itemPath = Path.Combine(path, fileName); - - var folderSize = await CalculateFolderSizeAsync(itemPath, token); - size += folderSize.size; - sizeOnDisk += folderSize.sizeOnDisk; - ++count; - ViewModel.FoldersCount++; - } - - if (size > ViewModel.ItemSizeBytes || sizeOnDisk > ViewModel.ItemSizeOnDiskBytes) - { - await Dispatcher.EnqueueOrInvokeAsync(() => - { - ViewModel.ItemSizeBytes = size; - ViewModel.ItemSize = size.ToSizeString(); - ViewModel.ItemSizeOnDiskBytes = sizeOnDisk; - ViewModel.ItemSizeOnDisk = sizeOnDisk.ToSizeString(); - SetItemsCountString(); - }, - DispatcherQueuePriority.Low); - } - - if (token.IsCancellationRequested) - break; - } - while (PInvoke.FindNextFile(hFile, out findData)); - - return (size, sizeOnDisk); - } - else - { - return (0, 0); - } - } - } -} diff --git a/src/Files.App/ViewModels/Properties/Items/BaseProperties.cs b/src/Files.App/ViewModels/Properties/Items/BaseProperties.cs index fea3c613bb67..35c7344883d6 100644 --- a/src/Files.App/ViewModels/Properties/Items/BaseProperties.cs +++ b/src/Files.App/ViewModels/Properties/Items/BaseProperties.cs @@ -55,11 +55,7 @@ public async Task GetOtherPropertiesAsync(IStorageItemExtraProperties properties public async Task<(long size, long sizeOnDisk)> CalculateFolderSizeAsync(string path, CancellationToken token) { -#if WINDOWS - return await CalculateFolderSizeWindowsAsync(path, token); -#else return await CalculateFolderSizeLinuxAsync(path, token); -#endif } private async Task<(long size, long sizeOnDisk)> CalculateFolderSizeLinuxAsync(string path, CancellationToken token) diff --git a/src/Files.App/ViewModels/Properties/Items/CombinedProperties.cs b/src/Files.App/ViewModels/Properties/Items/CombinedProperties.cs index c961184a9dbc..b9b7b0163dbf 100644 --- a/src/Files.App/ViewModels/Properties/Items/CombinedProperties.cs +++ b/src/Files.App/ViewModels/Properties/Items/CombinedProperties.cs @@ -20,9 +20,6 @@ public CombinedProperties( { List = listedItems; GetBaseProperties(); -#if WINDOWS - ViewModel.PropertyChanged += ViewModel_PropertyChanged; -#endif } public sealed override void GetBaseProperties() @@ -62,103 +59,6 @@ public override async Task GetSpecialPropertiesAsync() return; } -#if WINDOWS - var itemsWithPaths = List.Select(item => ( - Item: item, - Path: item.GetRequiredPath())).ToList(); - bool allFiles = true, allReadOnly = true, allNotReadOnly = true, allHidden = true, allNotHidden = true; - bool allCompressed = true, allNotCompressed = true, anyCanCompress = false; - foreach (var (x, path) in itemsWithPaths) - { - allFiles &= x.PrimaryItemAttribute == StorageItemTypes.File; - var fileAttributes = Win32Helper.GetFileAttributes(path); - bool isReadOnly = fileAttributes.HasFlag(System.IO.FileAttributes.ReadOnly); - allReadOnly &= isReadOnly; - allNotReadOnly &= !isReadOnly; - bool isHidden = fileAttributes.HasFlag(System.IO.FileAttributes.Hidden); - allHidden &= isHidden; - allNotHidden &= !isHidden; - bool isCompressed = fileAttributes.HasFlag(System.IO.FileAttributes.Compressed); - allCompressed &= isCompressed; - allNotCompressed &= !isCompressed; - anyCanCompress |= Win32Helper.CanCompressContent(path); - } - - if (allFiles) - { - if (allReadOnly) - ViewModel.IsReadOnly = true; - else if (allNotReadOnly) - ViewModel.IsReadOnly = false; - else - ViewModel.IsReadOnly = null; - } - - if (allHidden) - ViewModel.IsHidden = true; - else if (allNotHidden) - ViewModel.IsHidden = false; - else - ViewModel.IsHidden = null; - - ViewModel.CanCompressContent = anyCanCompress; - if (allCompressed) - ViewModel.IsContentCompressed = true; - else if (allNotCompressed) - ViewModel.IsContentCompressed = false; - else - ViewModel.IsContentCompressed = null; - - ViewModel.LastSeparatorVisibility = false; - ViewModel.ItemSizeVisibility = true; - - ViewModel.FilesCount += List.Count(x => x.PrimaryItemAttribute == StorageItemTypes.File || x.IsArchive); - ViewModel.FoldersCount += List.Count(x => x.PrimaryItemAttribute == StorageItemTypes.Folder && !x.IsArchive); - - long filesSize = List.Where(x => x.PrimaryItemAttribute == StorageItemTypes.File).Sum(x => x.FileSizeBytes); - long foldersSize = 0; - long filesSizeOnDisk = itemsWithPaths.Where(x => x.Item.PrimaryItemAttribute == StorageItemTypes.File && - x.Item.SyncStatusUI.SyncStatus is not CloudDriveSyncStatus.FileOnline and not CloudDriveSyncStatus.FolderOnline) - .Sum(x => Win32Helper.GetFileSizeOnDisk(x.Path) ?? 0); - long foldersSizeOnDisk = 0; - - ViewModel.ItemSizeProgressVisibility = true; - ViewModel.ItemSizeOnDiskProgressVisibility = true; - - foreach (var (item, path) in itemsWithPaths) - { - if (item.PrimaryItemAttribute == StorageItemTypes.Folder) - { - if (item.SyncStatusUI.SyncStatus is CloudDriveSyncStatus.FileOnline or - CloudDriveSyncStatus.FolderOnline or - CloudDriveSyncStatus.FolderOfflinePartial) - continue; - - var folderSizeTask = Task.Run(() => CalculateFolderSizeAsync(path, TokenSource.Token)); - - try - { - var folderSize = await folderSizeTask; - foldersSize += folderSize.size; - foldersSizeOnDisk += folderSize.sizeOnDisk; - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - } - } - - ViewModel.ItemSizeProgressVisibility = false; - ViewModel.ItemSizeOnDiskProgressVisibility = false; - - long totalSize = filesSize + foldersSize; - ViewModel.ItemSize = totalSize.ToLongSizeString(); - long totalSizeOnDisk = filesSizeOnDisk + foldersSizeOnDisk; - ViewModel.ItemSizeOnDisk = totalSizeOnDisk.ToLongSizeString(); - - SetItemsCountString(); -#endif } private async Task GetSpecialPropertiesLinuxAsync() @@ -216,66 +116,5 @@ private async Task GetSpecialPropertiesLinuxAsync() SetItemsCountString(); } -#if WINDOWS - private async void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) - { - if (OperatingSystem.IsLinux()) - return; - - switch (e.PropertyName) - { - case "IsReadOnly": - { - if (ViewModel.IsReadOnly is not null) - { - var itemPaths = List.Select(item => item.GetRequiredPath()).ToList(); - if ((bool)ViewModel.IsReadOnly) - { - itemPaths.ForEach(path => Win32Helper.SetFileAttribute( - path, System.IO.FileAttributes.ReadOnly)); - } - else - { - itemPaths.ForEach(path => Win32Helper.UnsetFileAttribute( - path, System.IO.FileAttributes.ReadOnly)); - } - } - } - break; - - case "IsHidden": - { - if (ViewModel.IsHidden is not null) - { - var itemPaths = List.Select(item => item.GetRequiredPath()).ToList(); - if ((bool)ViewModel.IsHidden) - { - itemPaths.ForEach(path => Win32Helper.SetFileAttribute( - path, System.IO.FileAttributes.Hidden)); - } - else - { - itemPaths.ForEach(path => Win32Helper.UnsetFileAttribute( - path, System.IO.FileAttributes.Hidden)); - } - } - - } - break; - - case "IsContentCompressed": - { - var isCompressed = ViewModel.IsContentCompressed ?? false; - var items = List.Select(item => item.GetRequiredPath()).ToList(); - await Task.Run(() => - { - foreach (var path in items) - Win32Helper.SetCompressionAttributeIoctl(path, isCompressed); - }); - } - break; - } - } -#endif } } diff --git a/src/Files.App/ViewModels/Properties/Items/FileProperties.cs b/src/Files.App/ViewModels/Properties/Items/FileProperties.cs index dfa71bca65ca..064694746ad7 100644 --- a/src/Files.App/ViewModels/Properties/Items/FileProperties.cs +++ b/src/Files.App/ViewModels/Properties/Items/FileProperties.cs @@ -24,9 +24,6 @@ public FileProperties( GetBaseProperties(); -#if WINDOWS - ViewModel.PropertyChanged += ViewModel_PropertyChanged; -#endif } public override void GetBaseProperties() @@ -43,9 +40,6 @@ public override void GetBaseProperties() ViewModel.LoadCustomIcon = Item.LoadCustomIcon; ViewModel.CustomIconSource = Item.CustomIconSource; ViewModel.LoadFileIcon = Item.LoadFileIcon; -#if WINDOWS - ViewModel.IsDownloadedFile = Win32Helper.ReadStringFromFile($"{itemPath}:Zone.Identifier") is not null; -#endif ViewModel.IsEditAlbumCoverVisible = Item.FileExtension is not ".avi" && ( FileExtensionHelpers.IsVideoFile(Item.FileExtension) || @@ -57,52 +51,6 @@ public override void GetBaseProperties() return; } -#if WINDOWS - if (!Item.IsShortcut) - return; - - var shortcutItem = (IShortcutItem)Item; - - var isApplication = - FileExtensionHelpers.IsExecutableFile(shortcutItem.TargetPath) || - FileExtensionHelpers.IsMsiFile(shortcutItem.TargetPath); - - ViewModel.ShortcutItemType = isApplication ? Strings.Application.GetLocalizedResource() : - Item.IsLinkItem ? Strings.PropertiesShortcutTypeLink.GetLocalizedResource() : Strings.File.GetLocalizedResource(); - ViewModel.ShortcutItemPath = shortcutItem.TargetPath; - ViewModel.IsShortcutItemPathReadOnly = shortcutItem.IsSymLink; - ViewModel.ShortcutItemWorkingDir = shortcutItem.WorkingDirectory; - ViewModel.ShortcutItemWorkingDirVisibility = Item.IsLinkItem || shortcutItem.IsSymLink ? false : true; - ViewModel.ShortcutItemArguments = shortcutItem.Arguments; - ViewModel.ShowWindowCommand = (ShowWindowCommand)(int)shortcutItem.ShowWindowCommand; - ViewModel.ShortcutItemArgumentsVisibility = Item.IsLinkItem || shortcutItem.IsSymLink ? false : true; - ViewModel.ShortcutItemWindowArgsVisibility = Item.IsLinkItem || shortcutItem.IsSymLink ? false : true; - - if (isApplication) - ViewModel.RunAsAdmin = shortcutItem.RunAsAdmin; - - ViewModel.IsSelectedItemShortcut = FileExtensionHelpers.IsShortcutFile(Item.FileExtension); - - ViewModel.ShortcutItemOpenLinkCommand = new RelayCommand(async () => - { - var shortcutPath = ViewModel.ShortcutItemPath - ?? throw new InvalidOperationException("The shortcut does not have a target path."); - - if (Item.IsLinkItem) - { - await Win32Helper.InvokeWin32ComponentAsync(shortcutPath, AppInstance, ViewModel.ShortcutItemArguments, ViewModel.RunAsAdmin, ViewModel.ShortcutItemWorkingDir); - } - else - { - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync( - () => NavigationHelpers.OpenPathInNewTab(Path.GetDirectoryName(shortcutPath), true)); - } - }, - () => - { - return !string.IsNullOrWhiteSpace(ViewModel.ShortcutItemPath); - }); -#endif } private void SetupLinuxShortcut(string itemPath) @@ -173,81 +121,6 @@ public override async Task GetSpecialPropertiesAsync() return; } -#if WINDOWS - // Check if item is on device (not online) - var isOnDevice = Item.SyncStatusUI.SyncStatus is not CloudDriveSyncStatus.FileOnline and not CloudDriveSyncStatus.FolderOnline; - - // Set basic file attributes - FileAttributes fileAttributes = Win32Helper.GetFileAttributes(itemPath); - ViewModel.IsReadOnly = fileAttributes.HasFlag(FileAttributes.ReadOnly); - ViewModel.IsHidden = fileAttributes.HasFlag(FileAttributes.Hidden); - ViewModel.CanCompressContent = Win32Helper.CanCompressContent(itemPath); - ViewModel.ItemSizeVisibility = true; - ViewModel.ItemSize = Item.FileSizeBytes.ToLongSizeString(); - - // Only check the compressed attribute and size on disk for items on the device - if (isOnDevice) - { - ViewModel.IsContentCompressed = fileAttributes.HasFlag(FileAttributes.Compressed); - ViewModel.ItemSizeOnDisk = Win32Helper.GetFileSizeOnDisk(itemPath)?.ToLongSizeString() ?? string.Empty; - } - - // Load icon - var result = await FileThumbnailHelper.GetIconAsync( - itemPath, - Constants.ShellIconSizes.ExtraLarge, - false, - IconOptions.None); - - if (result is not null) - { - ViewModel.IconData = result; - ViewModel.LoadUnknownTypeGlyph = false; - ViewModel.LoadFileIcon = true; - } - - // Handle shortcut properties - if (Item.IsShortcut) - { - ViewModel.ItemCreatedTimestampReal = Item.ItemDateCreatedReal; - ViewModel.ItemAccessedTimestampReal = Item.ItemDateAccessedReal; - - if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((IShortcutItem)Item).TargetPath)) - { - // Can't show any other property - return; - } - } - - // Get file for further processing - var targetPath = (Item as IShortcutItem)?.TargetPath; - string filePath = !string.IsNullOrEmpty(targetPath) ? targetPath : itemPath; - var shellViewModel = AppInstance.GetRequiredShellViewModel(); - - // Couldn't access the file and can't load any other properties - var fileResult = await shellViewModel.GetFileFromPathAsync(filePath); - if (fileResult.Result is not { } file) - return; - - // Can't load any other properties - if (Item.IsShortcut) - return; - - // Load uncompressed size for browsable zip files on device - if (isOnDevice && FileExtensionHelpers.IsBrowsableZipFile(Item.FileExtension, out _)) - { - if (await ZipStorageFolder.FromPathAsync(itemPath) is ZipStorageFolder zipFolder) - { - var uncompressedSize = await zipFolder.GetUncompressedSize(); - ViewModel.UncompressedItemSize = uncompressedSize.ToLongSizeString(); - ViewModel.UncompressedItemSizeBytes = uncompressedSize; - } - } - - // Get other properties if available - if (file.Properties is not null) - _ = GetOtherPropertiesAsync(file.Properties); -#endif } public async Task GetSystemFilePropertiesAsync() @@ -392,55 +265,5 @@ public async Task ClearPropertiesAsync() _ = GetSystemFilePropertiesAsync(); } -#if WINDOWS - private async void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) - { - if (OperatingSystem.IsLinux()) - return; - - var itemPath = Item.GetRequiredPath(); - - switch (e.PropertyName) - { - case nameof(ViewModel.IsReadOnly): - if (ViewModel.IsReadOnly is not null) - { - if ((bool)ViewModel.IsReadOnly) - Win32Helper.SetFileAttribute(itemPath, System.IO.FileAttributes.ReadOnly); - else - Win32Helper.UnsetFileAttribute(itemPath, System.IO.FileAttributes.ReadOnly); - } - - break; - - case nameof(ViewModel.IsHidden): - if (ViewModel.IsHidden is not null) - { - if ((bool)ViewModel.IsHidden) - Win32Helper.SetFileAttribute(itemPath, System.IO.FileAttributes.Hidden); - else - Win32Helper.UnsetFileAttribute(itemPath, System.IO.FileAttributes.Hidden); - } - - break; - - case nameof(ViewModel.IsContentCompressed): - Win32Helper.SetCompressionAttributeIoctl(itemPath, ViewModel.IsContentCompressed ?? false); - break; - - case nameof(ViewModel.RunAsAdmin): - case nameof(ViewModel.ShortcutItemPath): - case nameof(ViewModel.ShortcutItemWorkingDir): - case nameof(ViewModel.ShowWindowCommand): - case nameof(ViewModel.ShortcutItemArguments): - if (string.IsNullOrWhiteSpace(ViewModel.ShortcutItemPath)) - return; - - await FileOperationsHelpers.CreateOrUpdateLinkAsync(itemPath, ViewModel.ShortcutItemPath, ViewModel.ShortcutItemArguments, ViewModel.ShortcutItemWorkingDir, ViewModel.RunAsAdmin, (Windows.Win32.UI.WindowsAndMessaging.SHOW_WINDOW_CMD)(int)ViewModel.ShowWindowCommand); - - break; - } - } -#endif } } diff --git a/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs b/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs index d16657abae23..41abbf8d7981 100644 --- a/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs +++ b/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs @@ -26,9 +26,6 @@ public FolderProperties( GetBaseProperties(); -#if WINDOWS - ViewModel.PropertyChanged += ViewModel_PropertyChanged; -#endif } public override void GetBaseProperties() @@ -52,31 +49,6 @@ public override void GetBaseProperties() return; } -#if WINDOWS - if (Item.IsShortcut && Item is IShortcutItem shortcutItem) - { - ViewModel.ShortcutItemType = Strings.Folder.GetLocalizedResource(); - ViewModel.ShortcutItemPath = shortcutItem.TargetPath; - ViewModel.IsShortcutItemPathReadOnly = false; - ViewModel.ShortcutItemWorkingDir = shortcutItem.WorkingDirectory; - ViewModel.ShowWindowCommand = (ShowWindowCommand)(int)shortcutItem.ShowWindowCommand; - ViewModel.ShortcutItemWorkingDirVisibility = false; - ViewModel.ShortcutItemArguments = shortcutItem.Arguments; - ViewModel.ShortcutItemArgumentsVisibility = false; - ViewModel.ShortcutItemWindowArgsVisibility = false; - ViewModel.ShortcutItemOpenLinkCommand = new RelayCommand(async () => - { - var shortcutPath = ViewModel.ShortcutItemPath - ?? throw new InvalidOperationException("The shortcut does not have a target path."); - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync( - () => NavigationHelpers.OpenPathInNewTab(Path.GetDirectoryName(Environment.ExpandEnvironmentVariables(shortcutPath)), true)); - }, - () => - { - return !string.IsNullOrWhiteSpace(ViewModel.ShortcutItemPath); - }); - } -#endif } private void SetupLinuxLink(string itemPath) @@ -139,97 +111,6 @@ public async override Task GetSpecialPropertiesAsync() return; } -#if WINDOWS - var fileAttributes = Win32Helper.GetFileAttributes(itemPath); - ViewModel.IsHidden = fileAttributes.HasFlag(FileAttributes.Hidden); - ViewModel.CanCompressContent = Win32Helper.CanCompressContent(itemPath); - ViewModel.IsContentCompressed = fileAttributes.HasFlag(FileAttributes.Compressed); - - var result = await FileThumbnailHelper.GetIconAsync( - itemPath, - Constants.ShellIconSizes.ExtraLarge, - true, - IconOptions.None); - - if (result is not null) - { - ViewModel.IconData = result; - ViewModel.LoadFolderGlyph = false; - ViewModel.LoadFileIcon = true; - } - - if (Item.IsShortcut) - { - ViewModel.ItemSizeVisibility = true; - ViewModel.ItemSize = Item.FileSizeBytes.ToLongSizeString(); - - // Only load the size for items on the device - if (Item.SyncStatusUI.SyncStatus is not CloudDriveSyncStatus.FileOnline and not CloudDriveSyncStatus.FolderOnline) - ViewModel.ItemSizeOnDisk = Win32Helper.GetFileSizeOnDisk(itemPath)?.ToLongSizeString() ?? - string.Empty; - - ViewModel.ItemCreatedTimestampReal = Item.ItemDateCreatedReal; - ViewModel.ItemAccessedTimestampReal = Item.ItemDateAccessedReal; - if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((IShortcutItem)Item).TargetPath)) - { - // Can't show any other property - return; - } - } - - var targetPath = (Item as IShortcutItem)?.TargetPath; - string folderPath = !string.IsNullOrEmpty(targetPath) ? targetPath : Item.GetRequiredPath(); - var shellViewModel = AppInstance.GetRequiredShellViewModel(); - - var storageFolder = (await shellViewModel.GetFolderFromPathAsync(folderPath)).Result; - - if (storageFolder is not null) - { - ViewModel.ItemCreatedTimestampReal = storageFolder.DateCreated; - if (storageFolder.Properties is not null) - _ = GetOtherPropertiesAsync(storageFolder.Properties); - - // Only load the size for items on the device - if (Item.SyncStatusUI.SyncStatus is not CloudDriveSyncStatus.FileOnline and not - CloudDriveSyncStatus.FolderOnline and not - CloudDriveSyncStatus.FolderOfflinePartial) - _ = GetFolderSizeAsync(storageFolder.Path, TokenSource.Token); - } - else if (string.Equals(Item.ItemPath, Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - { - var recycleBinQuery = StorageTrashBinService.QueryRecycleBin(); - if (recycleBinQuery.BinSize is long binSize) - { - ViewModel.ItemSizeBytes = binSize; - ViewModel.ItemSize = ByteSize.FromBytes(binSize).ToString(); - ViewModel.ItemSizeVisibility = true; - } - else - { - ViewModel.ItemSizeVisibility = false; - } - ViewModel.ItemSizeOnDisk = string.Empty; - if (recycleBinQuery.NumItems is long numItems) - { - ViewModel.FilesCount = (int)numItems; - SetItemsCountString(); - ViewModel.FilesAndFoldersCountVisibility = true; - } - else - { - ViewModel.FilesAndFoldersCountVisibility = false; - } - - ViewModel.ItemCreatedTimestampVisibility = false; - ViewModel.ItemAccessedTimestampVisibility = false; - ViewModel.ItemModifiedTimestampVisibility = false; - ViewModel.LastSeparatorVisibility = false; - } - else - { - _ = GetFolderSizeAsync(folderPath, TokenSource.Token); - } -#endif } private async Task GetFolderSizeAsync(string folderPath, CancellationToken token) @@ -270,42 +151,5 @@ private async Task GetFolderSizeAsync(string folderPath, CancellationToken token SetItemsCountString(); } -#if WINDOWS - private async void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) - { - if (OperatingSystem.IsLinux()) - return; - - var itemPath = Item.GetRequiredPath(); - switch (e.PropertyName) - { - case nameof(ViewModel.IsHidden): - if (ViewModel.IsHidden is not null) - { - if ((bool)ViewModel.IsHidden) - Win32Helper.SetFileAttribute(itemPath, System.IO.FileAttributes.Hidden); - else - Win32Helper.UnsetFileAttribute(itemPath, System.IO.FileAttributes.Hidden); - } - break; - - case nameof(ViewModel.IsContentCompressed): - Win32Helper.SetCompressionAttributeIoctl(itemPath, ViewModel.IsContentCompressed ?? false); - break; - - case nameof(ViewModel.ShortcutItemPath): - case nameof(ViewModel.ShortcutItemWorkingDir): - case nameof(ViewModel.ShowWindowCommand): - case nameof(ViewModel.ShortcutItemArguments): - var shortcutItem = (IShortcutItem)Item; - - if (string.IsNullOrWhiteSpace(ViewModel.ShortcutItemPath)) - return; - - await FileOperationsHelpers.CreateOrUpdateLinkAsync(itemPath, ViewModel.ShortcutItemPath, ViewModel.ShortcutItemArguments, ViewModel.ShortcutItemWorkingDir, shortcutItem.RunAsAdmin, (Windows.Win32.UI.WindowsAndMessaging.SHOW_WINDOW_CMD)(int)ViewModel.ShowWindowCommand); - break; - } - } -#endif } } diff --git a/src/Files.App/ViewModels/Properties/Items/LibraryProperties.cs b/src/Files.App/ViewModels/Properties/Items/LibraryProperties.cs index eccb2a35f8e5..f72f6f24feb7 100644 --- a/src/Files.App/ViewModels/Properties/Items/LibraryProperties.cs +++ b/src/Files.App/ViewModels/Properties/Items/LibraryProperties.cs @@ -44,12 +44,8 @@ public override void GetBaseProperties() public async override Task GetSpecialPropertiesAsync() { var libraryPath = Library.GetRequiredPath(); -#if WINDOWS - var fileAttributes = Win32Helper.GetFileAttributes(libraryPath); -#else // Windows libraries (.library-ms) don't exist on Linux var fileAttributes = default(System.IO.FileAttributes); -#endif ViewModel.IsReadOnly = fileAttributes.HasFlag(System.IO.FileAttributes.ReadOnly); ViewModel.IsHidden = fileAttributes.HasFlag(System.IO.FileAttributes.Hidden); ViewModel.CanCompressContent = false; @@ -146,33 +142,6 @@ private async Task GetLibrarySizeAsync(List storageFolders, C private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { -#if WINDOWS - var libraryPath = Library.GetRequiredPath(); - switch (e.PropertyName) - { - case "IsReadOnly": - if (ViewModel.IsReadOnly is not null) - { - if ((bool)ViewModel.IsReadOnly) - Win32Helper.SetFileAttribute(libraryPath, System.IO.FileAttributes.ReadOnly); - else - Win32Helper.UnsetFileAttribute(libraryPath, System.IO.FileAttributes.ReadOnly); - } - - break; - - case "IsHidden": - if (ViewModel.IsHidden is not null) - { - if ((bool)ViewModel.IsHidden) - Win32Helper.SetFileAttribute(libraryPath, System.IO.FileAttributes.Hidden); - else - Win32Helper.UnsetFileAttribute(libraryPath, System.IO.FileAttributes.Hidden); - } - - break; - } -#endif } } } diff --git a/src/Files.App/ViewModels/Properties/MainPropertiesViewModel.cs b/src/Files.App/ViewModels/Properties/MainPropertiesViewModel.cs index fa203b3e91d6..22ac737419a5 100644 --- a/src/Files.App/ViewModels/Properties/MainPropertiesViewModel.cs +++ b/src/Files.App/ViewModels/Properties/MainPropertiesViewModel.cs @@ -89,20 +89,8 @@ private void NavigateToPage(PropertiesNavigationItem item) PropertiesNavigationViewItemType.Shortcut => typeof(ShortcutPage), PropertiesNavigationViewItemType.Library => typeof(LibraryPage), PropertiesNavigationViewItemType.Details => typeof(DetailsPage), -#if WINDOWS - PropertiesNavigationViewItemType.Security => typeof(SecurityPage), -#endif PropertiesNavigationViewItemType.Permissions => typeof(PermissionsPage), -#if WINDOWS - PropertiesNavigationViewItemType.Customization => typeof(CustomizationPage), -#endif -#if WINDOWS - PropertiesNavigationViewItemType.Compatibility => typeof(CompatibilityPage), -#endif PropertiesNavigationViewItemType.Hashes => typeof(HashesPage), -#if WINDOWS - PropertiesNavigationViewItemType.Signatures => typeof(SignaturesPage), -#endif _ => typeof(GeneralPage), }; diff --git a/src/Files.App/ViewModels/Properties/SecurityAdvancedViewModel.Windows.cs b/src/Files.App/ViewModels/Properties/SecurityAdvancedViewModel.Windows.cs deleted file mode 100644 index ab6d1c0c504a..000000000000 --- a/src/Files.App/ViewModels/Properties/SecurityAdvancedViewModel.Windows.cs +++ /dev/null @@ -1,269 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Microsoft.UI.Xaml; -using Windows.Storage; - -namespace Files.App.ViewModels.Properties -{ - [WinRT.GeneratedBindableCustomProperty( - [ - nameof(ColumnTypeGridLength), - nameof(ColumnPrincipalGridLength), - nameof(ColumnAccessGridLength), - nameof(ColumnInheritedGridLength), - ], - [])] - public sealed partial class SecurityAdvancedViewModel : ObservableObject - { - private readonly IStorageSecurityService StorageSecurityService = Ioc.Default.GetRequiredService(); - - private readonly PropertiesPageNavigationParameter _navigationParameter; - - private readonly Window _window; - - private readonly string _path; - - private readonly bool _isFolder; - - public bool IsAddAccessControlEntryButtonEnabled => - AccessControlList is not null && - AccessControlList.IsValid; - - public bool IsDeleteAccessControlEntryButtonEnabled => - AccessControlList is not null && - AccessControlList.IsValid && - SelectedAccessControlEntry is not null && - SelectedAccessControlEntry.IsInherited is false; - - public IconFileInfo ShieldIconFileInfo { get; private set; } - - public bool CurrentInstanceCanReadPermissions { get; private set; } - - public bool CurrentInstanceCanChangePermissions { get; private set; } - - public string DisableInheritanceOption - { - get - { - //if (!_isProtected) - // return "SecurityAdvancedInheritedEnable/Text".GetLocalizedResource(); - //else if (_preserveInheritance) - // return "SecurityAdvancedInheritedConvert/Text".GetLocalizedResource(); - //else - // return "SecurityAdvancedInheritedRemove/Text".GetLocalizedResource(); - - return string.Empty; - } - } - - private AccessControlList? _AccessControlList; - public AccessControlList AccessControlList - { - get => _AccessControlList - ?? throw new InvalidOperationException("The access control list has not been loaded."); - set => SetProperty(ref _AccessControlList, value); - } - - private AccessControlEntry? _SelectedAccessControlEntry; - public AccessControlEntry? SelectedAccessControlEntry - { - get => _SelectedAccessControlEntry; - set - { - // Previous selection - if (_SelectedAccessControlEntry is not null) - _SelectedAccessControlEntry.IsSelected = false; - - if (SetProperty(ref _SelectedAccessControlEntry, value)) - { - if (value is not null) - value.IsSelected = true; - - OnPropertyChanged(nameof(IsDeleteAccessControlEntryButtonEnabled)); - } - } - } - - private bool _DisplayElements; - public bool DisplayElements - { - get => _DisplayElements; - set => SetProperty(ref _DisplayElements, value); - } - - private string _ErrorMessage = string.Empty; - public string ErrorMessage - { - get => _ErrorMessage; - set => SetProperty(ref _ErrorMessage, value); - } - - private GridLength _ColumnTypeGridLength = new(64d); - public GridLength ColumnTypeGridLength - { - get => _ColumnTypeGridLength; - set => SetProperty(ref _ColumnTypeGridLength, value); - } - - private GridLength _ColumnPrincipalGridLength = new(200d); - public GridLength ColumnPrincipalGridLength - { - get => _ColumnPrincipalGridLength; - set => SetProperty(ref _ColumnPrincipalGridLength, value); - } - - private GridLength _ColumnAccessGridLength = new(160d); - public GridLength ColumnAccessGridLength - { - get => _ColumnAccessGridLength; - set => SetProperty(ref _ColumnAccessGridLength, value); - } - - private GridLength _ColumnInheritedGridLength = new(70d); - public GridLength ColumnInheritedGridLength - { - get => _ColumnInheritedGridLength; - set => SetProperty(ref _ColumnInheritedGridLength, value); - } - - public IAsyncRelayCommand ChangeOwnerCommand { get; set; } - public IAsyncRelayCommand AddAccessControlEntryCommand { get; set; } - public IAsyncRelayCommand RemoveAccessControlEntryCommand { get; set; } - - public SecurityAdvancedViewModel(PropertiesPageNavigationParameter parameter) - { - _navigationParameter = parameter; - _window = parameter.Window - ?? throw new InvalidOperationException("The security page does not have an associated window."); - - switch (parameter.Parameter) - { - case ListedItem listedItem: - _path = listedItem.GetRequiredPath(); - _isFolder = listedItem.PrimaryItemAttribute == StorageItemTypes.Folder && !listedItem.IsShortcut; - break; - case DriveItem driveItem: - _path = driveItem.GetRequiredPath(); - _isFolder = true; - break; - default: - throw new ArgumentException("The security page requires a listed item or drive.", nameof(parameter)); - } - ; - - ShieldIconFileInfo = LoadShieldIconResource(); - - LoadAccessControlEntry(); - - ChangeOwnerCommand = new AsyncRelayCommand(ExecuteChangeOwnerCommandAsync); - AddAccessControlEntryCommand = new AsyncRelayCommand(ExecuteAddAccessControlEntryCommandAsync); - RemoveAccessControlEntryCommand = new AsyncRelayCommand(ExecuteRemoveAccessControlEntryCommandAsync); - } - - private IconFileInfo LoadShieldIconResource() - { - string imageres = System.IO.Path.Combine(Constants.UserEnvironmentPaths.SystemRootPath, "System32", "imageres.dll"); - - var imageResList = Win32Helper.ExtractSelectedIconsFromDLL( - imageres, - new List() { Constants.ImageRes.ShieldIcon }, - 16); - - return imageResList.First(); - } - - private void LoadAccessControlEntry() - { - var error = StorageSecurityService.GetAcl(_path, _isFolder, out var accessControlList); - AccessControlList = accessControlList - ?? throw new InvalidOperationException("The security service did not return an access control list."); - OnPropertyChanged(nameof(AccessControlList)); - - SelectedAccessControlEntry = AccessControlList.AccessControlEntries.FirstOrDefault(); - - if (!AccessControlList.IsValid) - { - DisplayElements = false; - - if (error is FileSecurityResult.AccessDenied) - { - ErrorMessage = - Strings.SecurityRequireReadPermissions.GetLocalizedResource() + - "\r\n\r\n" + - Strings.SecuritySuggestToTakeOwnership.GetLocalizedResource(); - } - else - { - ErrorMessage = - Strings.SecurityUnableToDisplayPermissions.GetLocalizedResource() + - "\r\n\r\n" + - error.ToString(); - } - } - else - { - DisplayElements = true; - ErrorMessage = string.Empty; - } - } - - private async Task ExecuteChangeOwnerCommandAsync() - { - var sid = await FileOperationsHelpers.OpenObjectPickerAsync(FilePropertiesHelpers.GetWindowHandle(_window).ToInt64()); - if (string.IsNullOrEmpty(sid)) - return; - - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => - { - // Set owner - StorageSecurityService.SetOwner(_path, sid); - - // Reload - LoadAccessControlEntry(); - }); - } - - private async Task ExecuteAddAccessControlEntryCommandAsync() - { - // Pick an user or a group with Object Picker UI - var sid = await FileOperationsHelpers.OpenObjectPickerAsync(FilePropertiesHelpers.GetWindowHandle(_window).ToInt64()); - if (string.IsNullOrEmpty(sid)) - return; - - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => - { - // Run Win32API - var win32Result = StorageSecurityService.AddAce(_path, _isFolder, sid); - - // Add a new ACE to the ACL - var ace = AccessControlEntry.GetDefault(_isFolder, sid); - AccessControlList.AccessControlEntries.Insert(0, ace); - }); - } - - private async Task ExecuteRemoveAccessControlEntryCommandAsync() - { - if (SelectedAccessControlEntry is null) - return; - - await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(() => - { - // Get index of the ACE - var index = AccessControlList.AccessControlEntries.IndexOf(SelectedAccessControlEntry); - - // Run Win32API - var win32Result = StorageSecurityService.DeleteAce(_path, (uint)index); - - // Remove the ACE - AccessControlList.AccessControlEntries.Remove(SelectedAccessControlEntry); - - if (AccessControlList.AccessControlEntries.Count == 0) - return; - - // Re-select item - SelectedAccessControlEntry = AccessControlList.AccessControlEntries.First(); - }); - } - } -} diff --git a/src/Files.App/ViewModels/Properties/SecurityViewModel.Windows.cs b/src/Files.App/ViewModels/Properties/SecurityViewModel.Windows.cs deleted file mode 100644 index da0418ab4d48..000000000000 --- a/src/Files.App/ViewModels/Properties/SecurityViewModel.Windows.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using CommunityToolkit.WinUI; -using Microsoft.UI.Xaml; -using Windows.Storage; - -namespace Files.App.ViewModels.Properties -{ - public sealed partial class SecurityViewModel : ObservableObject - { - private readonly IStorageSecurityService StorageSecurityService = Ioc.Default.GetRequiredService(); - - private readonly PropertiesPageNavigationParameter _navigationParameter; - - private readonly Window _window; - - private readonly string _path; - - private readonly bool _isFolder; - - public bool DisplayElements { get; private set; } - - public string ErrorMessage { get; private set; } - - public bool IsAddAccessControlEntryButtonEnabled => - AccessControlList is not null && - AccessControlList.IsValid; - - public bool IsDeleteAccessControlEntryButtonEnabled => - AccessControlList is not null && - AccessControlList.IsValid && - SelectedAccessControlEntry is not null && - SelectedAccessControlEntry.IsInherited is false; - - public string SelectedItemHeaderText => - SelectedAccessControlEntry is null - ? Strings.Permissions.GetLocalizedResource() - : string.Format(Strings.SecurityPermissionsHeaderText.GetLocalizedResource(), SelectedAccessControlEntry?.Principal.DisplayName); - - private AccessControlList? _AccessControlList; - public AccessControlList AccessControlList - { - get => _AccessControlList - ?? throw new InvalidOperationException("The access control list has not been loaded."); - set => SetProperty(ref _AccessControlList, value); - } - - private AccessControlEntry? _SelectedAccessControlEntry; - public AccessControlEntry? SelectedAccessControlEntry - { - get => _SelectedAccessControlEntry; - set - { - // Previous selection - if (_SelectedAccessControlEntry is not null) - _SelectedAccessControlEntry.IsSelected = false; - - if (value is not null && SetProperty(ref _SelectedAccessControlEntry, value)) - { - value.IsSelected = true; - - OnPropertyChanged(nameof(IsDeleteAccessControlEntryButtonEnabled)); - OnPropertyChanged(nameof(SelectedItemHeaderText)); - } - } - } - - public IAsyncRelayCommand AddAccessControlEntryCommand { get; set; } - public IAsyncRelayCommand RemoveAccessControlEntryCommand { get; set; } - - public SecurityViewModel(PropertiesPageNavigationParameter parameter) - { - _navigationParameter = parameter; - _window = parameter.Window - ?? throw new InvalidOperationException("The security page does not have an associated window."); - - switch (parameter.Parameter) - { - case ListedItem listedItem: - _path = listedItem.GetRequiredPath(); - _isFolder = listedItem.PrimaryItemAttribute == StorageItemTypes.Folder && !listedItem.IsShortcut; - break; - case DriveItem driveItem: - _path = driveItem.GetRequiredPath(); - _isFolder = true; - break; - default: - throw new ArgumentException("The security page requires a listed item or drive.", nameof(parameter)); - } - ; - - var error = StorageSecurityService.GetAcl(_path, _isFolder, out var accessControlList); - AccessControlList = accessControlList - ?? throw new InvalidOperationException("The security service did not return an access control list."); - _SelectedAccessControlEntry = AccessControlList.AccessControlEntries.FirstOrDefault(); - - if (!AccessControlList.IsValid) - { - DisplayElements = false; - ErrorMessage = error is FileSecurityResult.AccessDenied - ? Strings.SecurityRequireReadPermissions.GetLocalizedResource() + "\r\n" + Strings.SecurityClickAdvancedPermissions.GetLocalizedResource() - : Strings.SecurityUnableToDisplayPermissions.GetLocalizedResource(); - } - else - { - DisplayElements = true; - ErrorMessage = string.Empty; - } - - AddAccessControlEntryCommand = new AsyncRelayCommand(ExecuteAddAccessControlEntryCommandAsync); - RemoveAccessControlEntryCommand = new AsyncRelayCommand(ExecuteRemoveAccessControlEntryCommandAsync); - } - - private async Task ExecuteAddAccessControlEntryCommandAsync() - { - // Pick an user or a group with Object Picker UI - var sid = await FileOperationsHelpers.OpenObjectPickerAsync(FilePropertiesHelpers.GetWindowHandle(_window).ToInt64()); - if (string.IsNullOrEmpty(sid)) - return; - - await MainWindow.Instance.DispatcherQueue.EnqueueAsync(() => - { - // Run Win32API - var win32Result = StorageSecurityService.AddAce(_path, _isFolder, sid); - - // Add a new ACE to the ACL - var ace = AccessControlEntry.GetDefault(_isFolder, sid); - AccessControlList.AccessControlEntries.Insert(0, ace); - }); - } - - private async Task ExecuteRemoveAccessControlEntryCommandAsync() - { - var selectedEntry = SelectedAccessControlEntry - ?? throw new InvalidOperationException("No access control entry is selected for removal."); - - await MainWindow.Instance.DispatcherQueue.EnqueueAsync(() => - { - // Get index of the ACE - var index = AccessControlList.AccessControlEntries.IndexOf(selectedEntry); - if (index < 0) - throw new InvalidOperationException("The selected access control entry is not part of the access control list."); - - // Run Win32API - var win32Result = StorageSecurityService.DeleteAce(_path, (uint)index); - - // Remove the ACE - AccessControlList.AccessControlEntries.Remove(selectedEntry); - - if (AccessControlList.AccessControlEntries.Count == 0) - return; - - // Re-select item - SelectedAccessControlEntry = AccessControlList.AccessControlEntries.First(); - }); - } - } -} diff --git a/src/Files.App/ViewModels/Properties/SignaturesViewModel.Windows.cs b/src/Files.App/ViewModels/Properties/SignaturesViewModel.Windows.cs deleted file mode 100644 index fc3addbdb636..000000000000 --- a/src/Files.App/ViewModels/Properties/SignaturesViewModel.Windows.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Utils.Signatures; -using Microsoft.UI.Windowing; -using Windows.Win32.Foundation; - -namespace Files.App.ViewModels.Properties -{ - public sealed partial class SignaturesViewModel : ObservableObject, IDisposable - { - private CancellationTokenSource _cancellationTokenSource; - - public ObservableCollection Signatures { get; set; } - - public bool NoSignatureFound => Signatures.Count == 0; - - public SignaturesViewModel(ListedItem item, AppWindow appWindow) - { - _cancellationTokenSource = new(); - Signatures = new(); - var hWnd = new HWND(Microsoft.UI.Win32Interop.GetWindowFromWindowId(appWindow.Id)); - Signatures.CollectionChanged += (s, e) => OnPropertyChanged(nameof(NoSignatureFound)); - DigitalSignaturesUtil.LoadItemSignatures( - item.ItemPath!, - Signatures, - hWnd, - _cancellationTokenSource.Token - ); - } - - public void Dispose() - { - _cancellationTokenSource.Cancel(); - } - } -} diff --git a/src/Files.App/ViewModels/Settings/AboutViewModel.cs b/src/Files.App/ViewModels/Settings/AboutViewModel.cs index 9f424818037f..10f77900743c 100644 --- a/src/Files.App/ViewModels/Settings/AboutViewModel.cs +++ b/src/Files.App/ViewModels/Settings/AboutViewModel.cs @@ -32,11 +32,7 @@ public string AppName public Microsoft.UI.Xaml.Visibility WindowsOnlyVisibility => OperatingSystem.IsWindows() ? Microsoft.UI.Xaml.Visibility.Visible : Microsoft.UI.Xaml.Visibility.Collapsed; -#if WINDOWS - public PackageVersion AppVersion => Package.Current.Id.Version; -#else public System.Version AppVersion => typeof(AboutViewModel).Assembly.GetName().Version ?? new System.Version(); -#endif public ObservableCollection OpenSourceLibraries { get; } diff --git a/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs b/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs index 6b84d2e88723..2a925b49c032 100644 --- a/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs +++ b/src/Files.App/ViewModels/Settings/AdvancedViewModel.cs @@ -4,9 +4,6 @@ using Microsoft.Extensions.Logging; using Microsoft.UI.Xaml; using Microsoft.Win32; -#if WINDOWS -using SevenZip; -#endif using System.IO; using System.Runtime.InteropServices; using System.Text; @@ -14,9 +11,6 @@ using Windows.ApplicationModel; using Windows.Storage; using Windows.Storage.Pickers; -#if WINDOWS -using Windows.Win32.Storage.FileSystem; -#endif namespace Files.App.ViewModels.Settings { @@ -77,25 +71,6 @@ private async Task SetAsDefaultExplorerAsync() } } -#if WINDOWS - var dataPath = Environment.ExpandEnvironmentVariables("%LocalAppData%\\Files"); - if (IsSetAsDefaultFileManager) - { - var sourcePath = Path.Combine(destFolder, "*"); - var branchPath = Path.Combine(dataPath, "Branch.txt"); - var command = $"-command \"New-Item -Force -Path {Win32Helper.ToPowerShellStringLiteral(dataPath)} -ItemType Directory; Copy-Item -Filter *.* -Path {Win32Helper.ToPowerShellStringLiteral(sourcePath)} -Recurse -Force -Destination {Win32Helper.ToPowerShellStringLiteral(dataPath)}; 'files-dev' | Out-File -Encoding utf8 -Force -FilePath {Win32Helper.ToPowerShellStringLiteral(branchPath)}\""; - if (!await Win32Helper.RunPowershellCommandAsync(command, PowerShellExecutionOptions.Hidden)) - { - // Error copying files - await DetectResult(); - return; - } - } - else - { - await Win32Helper.RunPowershellCommandAsync($"-command \"Remove-Item -LiteralPath {Win32Helper.ToPowerShellStringLiteral(dataPath)} -Recurse -Force\"", PowerShellExecutionOptions.Hidden); - } -#endif try { @@ -223,38 +198,14 @@ private async Task ExportSettingsAsync() try { -#if WINDOWS - if (OperatingSystem.IsWindows()) - { - var handle = Win32PInvoke.CreateFileFromAppW( - filePath, - (uint)(FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE), - Win32PInvoke.FILE_SHARE_READ | Win32PInvoke.FILE_SHARE_WRITE, - nint.Zero, - Win32PInvoke.CREATE_NEW, - 0, - nint.Zero); - - Win32PInvoke.CloseHandle(handle); - } - else - { - using (new FileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) { } - } -#else using (new FileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite)) { } -#endif var file = await StorageHelpers.ToStorageItem(filePath); if (file is null) throw new IOException($"The settings export file '{filePath}' could not be opened."); -#if WINDOWS - await ZipStorageFolder.InitArchive(file, OutArchiveFormat.Zip); -#else // LINUX-TODO(settings): migrate legacy settings import/export to IArchiveService. await ZipStorageFolder.InitArchive(file, ArchiveFormats.Zip); -#endif if (await ZipStorageFolder.FromStorageFileAsync(file) is not ZipStorageFolder zipFolder) return; diff --git a/src/Files.App/ViewModels/Settings/DevToolsViewModel.cs b/src/Files.App/ViewModels/Settings/DevToolsViewModel.cs index 31e686178d60..027edf019189 100644 --- a/src/Files.App/ViewModels/Settings/DevToolsViewModel.cs +++ b/src/Files.App/ViewModels/Settings/DevToolsViewModel.cs @@ -194,12 +194,6 @@ private async void DoTestIDE() return; } -#if WINDOWS - IsIDEPathValid = await Win32Helper.RunPowershellCommandAsync( - $"& {Win32Helper.ToPowerShellStringLiteral(IDEPath)}", - PowerShellExecutionOptions.Hidden - ); -#endif } private bool CheckPathExists() diff --git a/src/Files.App/ViewModels/Settings/GeneralViewModel.cs b/src/Files.App/ViewModels/Settings/GeneralViewModel.cs index 2f58a8538561..0e055e32352d 100644 --- a/src/Files.App/ViewModels/Settings/GeneralViewModel.cs +++ b/src/Files.App/ViewModels/Settings/GeneralViewModel.cs @@ -564,11 +564,7 @@ public bool ShowOpenInNewWindow } public string ShowOpenTerminalText -#if WINDOWS - => Strings.ShowOpenTerminal.GetLocalizedResource(); -#else => Strings.ShowOpenTerminalLinux.GetLocalizedResource(); -#endif public bool ShowOpenTerminal { diff --git a/src/Files.App/ViewModels/ShellViewModel.Windows.cs b/src/Files.App/ViewModels/ShellViewModel.Windows.cs deleted file mode 100644 index 772e11ccca35..000000000000 --- a/src/Files.App/ViewModels/ShellViewModel.Windows.cs +++ /dev/null @@ -1,938 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using Microsoft.Extensions.Logging; -using System.Collections.Concurrent; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Windows.Foundation; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.Storage.Search; -using Windows.Win32; -using Windows.Win32.System.SystemServices; -using static Files.App.Helpers.Win32PInvoke; -using ByteSize = ByteSizeLib.ByteSize; -using FileAttributes = System.IO.FileAttributes; - -namespace Files.App.ViewModels -{ - /// - /// Windows folder listing (FindFirstFileEx, StorageFolder queries), ReadDirectoryChangesW watchers, alternate data streams and - /// Recycle Bin shell items of . Kept byte-identical to upstream where possible. - /// - public sealed partial class ShellViewModel - { - private async void RecycleBinRefreshRequestedAsync(object? sender, FileSystemEventArgs e) - { - if (!Constants.UserEnvironmentPaths.RecycleBinPath.Equals(CurrentFolder?.ItemPath, StringComparison.OrdinalIgnoreCase)) - return; - - await dispatcherQueue.EnqueueOrInvokeAsync(() => - { - RefreshItems(null); - }); - } - - private async void RecycleBinItemDeletedAsync(object? sender, FileSystemEventArgs e) - { - if (!Constants.UserEnvironmentPaths.RecycleBinPath.Equals(CurrentFolder?.ItemPath, StringComparison.OrdinalIgnoreCase)) - return; - - var removedItem = await RemoveFileOrFolderAsync(e.FullPath); - - if (removedItem is not null) - await ApplyFilesAndFoldersChangesAsync(); - } - - private async void RecycleBinItemCreatedAsync(object? sender, FileSystemEventArgs e) - { - if (!Constants.UserEnvironmentPaths.RecycleBinPath.Equals(CurrentFolder?.ItemPath, StringComparison.OrdinalIgnoreCase)) - return; - - using var folderItem = SafetyExtensions.IgnoreExceptions(() => new ShellItem(e.FullPath)); - if (folderItem is null) - return; - - var shellFileItem = ShellFolderExtensions.GetShellFileItem(folderItem); - if (shellFileItem is null) - throw new InvalidDataException("The recycle-bin item could not be converted to a shell item."); - - var newListedItem = await AddFileOrFolderFromShellFile(shellFileItem); - if (newListedItem is null) - return; - - await AddFileOrFolderAsync(newListedItem); - await OrderFilesAndFoldersAsync(); - await ApplyFilesAndFoldersChangesAsync(); - } - - partial void ApplyDriveStorageDetails(ListedItem item, IDictionary properties) - { - // Drive Storage Details - if (properties["System.SFGAOFlags"] is uint attributesRaw && - properties["System.Capacity"] is ulong capacityRaw && - properties["System.FreeSpace"] is ulong freeSpaceRaw && - ((SFGAO_FLAGS)attributesRaw).HasFlag(SFGAO_FLAGS.SFGAO_REMOVABLE) && - !((SFGAO_FLAGS)attributesRaw).HasFlag(SFGAO_FLAGS.SFGAO_FILESYSTEM)) - { - var maxSpace = ByteSize.FromBytes(capacityRaw); - var freeSpace = ByteSize.FromBytes(freeSpaceRaw); - - item.MaxSpace = maxSpace; - item.SpaceUsed = maxSpace - freeSpace; - item.FileSize = string.Format(Strings.DriveFreeSpaceAndCapacity.GetLocalizedResource(), freeSpace.ToSizeString(), maxSpace.ToSizeString()); - item.ShowDriveStorageDetails = true; - } - } - - private async Task PromptToUnlockBitlockerIfLockedAsync(string path, string pathRoot) - { - try - { - var rootFolder = await FilesystemTasks.WrapNullable(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path)); - if (await FolderHelpers.CheckBitlockerStatusAsync(rootFolder, path)) - await ContextMenu.InvokeVerb("unlock-bde", pathRoot); - } - catch (Exception ex) - { - // Runs detached, so swallow: the property probe or the unlock-bde shell verb can throw (e.g. COMException) - App.Logger.LogWarning(ex, ex.Message); - } - } - - private async Task EnumerateWindowsFolderAsync(string path, CancellationToken cancellationToken, LibraryItem? library) - { - // Flag to use FindFirstFileExFromApp or StorageFolder enumeration - Use storage folder for Box Drive (#4629) - var isBoxFolder = CloudDrivesManager.Drives.FirstOrDefault(x => x.Text == "Box")?.Path?.TrimEnd('\\') is string boxFolder && path.StartsWith(boxFolder); - bool isWslDistro = path.StartsWith(@"\\wsl$\", StringComparison.OrdinalIgnoreCase) || path.StartsWith(@"\\wsl.localhost\", StringComparison.OrdinalIgnoreCase) - || path.Equals(@"\\wsl$", StringComparison.OrdinalIgnoreCase) || path.Equals(@"\\wsl.localhost", StringComparison.OrdinalIgnoreCase); - bool isMtp = path.StartsWith(@"\\?\", StringComparison.Ordinal); - bool isShellFolder = path.StartsWith(@"\\SHELL\", StringComparison.Ordinal); - bool isNetwork = path.StartsWith(@"\\", StringComparison.Ordinal) && - !isMtp && - !isShellFolder && - !isWslDistro; - bool isNetdisk = false; - - try - { - // Special handling for network drives - if (!isNetwork) - isNetdisk = await Task.Run(() => new DriveInfo(path).DriveType == System.IO.DriveType.Network); - } - catch { } - - bool isFtp = FtpHelpers.IsFtpPath(path); - bool enumFromStorageFolder = isBoxFolder || isFtp; - - BaseStorageFolder? rootFolder = null; - - if (isNetwork || isNetdisk) - { - var auth = await NetworkService.AuthenticateNetworkShare(path, cancellationToken); - if (!auth) - return -1; - } - - // Off the UI thread: FindFirstFileEx blocks until the SMB timeout on an unreachable share. - Win32PInvoke.SafeFindHandle? hFile = null; - WIN32_FIND_DATA findData = default; - int errorCode = 0; - if (!enumFromStorageFolder) - { - (hFile, findData, errorCode) = await Task.Run(() => - { - var hFileTsk = FindFirstFileExFromAppSafe( - path + "\\*.*", - FINDEX_INFO_LEVELS.FindExInfoBasic, - out WIN32_FIND_DATA findDataTsk, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - IntPtr.Zero, - FIND_FIRST_EX_LARGE_FETCH); - - return (hFileTsk, findDataTsk, hFileTsk.IsInvalid ? Marshal.GetLastWin32Error() : 0); - }) - .WithTimeoutAsync(TimeSpan.FromSeconds(5)); - } - - if (!enumFromStorageFolder && hFile is not null && !hFile.IsInvalid) - { - // Enumerate with the handle opened above; rootFolder only used for Bitlocker - currentStorageFolder = null; - } - else if (workingRoot is not null) - { - var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, workingRoot, currentStorageFolder)); - if (!res) - return -1; - - var storageFolder = res.Result - ?? throw new InvalidOperationException("A successful folder lookup did not return a storage folder."); - - currentStorageFolder = storageFolder; - rootFolder = storageFolder.Item; - enumFromStorageFolder = true; - } - else - { - var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, workingRoot, currentStorageFolder)); - if (res) - { - var storageFolder = res.Result - ?? throw new InvalidOperationException("A successful folder lookup did not return a storage folder."); - currentStorageFolder = storageFolder; - rootFolder = storageFolder.Item; - } - else if (res == FileSystemStatusCode.Unauthorized) - { - ShowLocationInaccessibleOrMissing(path); - - return -1; - } - else if (res == FileSystemStatusCode.NotFound) - { - ShowLocationInaccessibleOrMissing(path); - - return -1; - } - else - { - ShowLocationUnavailable(LocationUnavailableKind.DriveUnplugged, res.ErrorCode.ToString()); - - return -1; - } - } - - var pathRoot = Path.GetPathRoot(path); - if (Path.IsPathRooted(path) && pathRoot == path) - { - // Off the critical path: a locked drive fails enumeration anyway, so don't block the listing on the BitLocker probe. - _ = PromptToUnlockBitlockerIfLockedAsync(path, pathRoot); - } - - HasNoWatcher = isFtp || isWslDistro || isMtp || currentStorageFolder?.Item is ZipStorageFolder; - - if (enumFromStorageFolder) - { - // The handle from the open above is unused on the storage-folder path. - hFile?.Dispose(); - - var basicProps = await rootFolder?.GetBasicPropertiesAsync(); - var currentFolder = library ?? new ListedItem(rootFolder?.FolderRelativeId ?? string.Empty) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemPropertiesInitialized = true, - ItemNameRaw = rootFolder?.DisplayName ?? string.Empty, - ItemDateModifiedReal = basicProps.DateModified, - ItemType = rootFolder?.DisplayType ?? string.Empty, - FileImage = null, - LoadFileIcon = false, - ItemPath = string.IsNullOrEmpty(rootFolder?.Path) ? currentStorageFolder?.Path ?? string.Empty : rootFolder.Path, - FileSize = null, - FileSizeBytes = 0, - }; - - if (library is null) - currentFolder.ItemDateCreatedReal = rootFolder?.DateCreated ?? DateTimeOffset.Now; - - CurrentFolder = currentFolder; - await EnumFromStorageFolderAsync(path, rootFolder, currentStorageFolder, cancellationToken); - - // Workaround for #7428 - return isBoxFolder ? 2 : 1; - } - else - { - var itemModifiedDate = DateTime.Now; - var itemCreatedDate = DateTime.Now; - - try - { - FileTimeToSystemTime(in findData.ftLastWriteTime, out var systemModifiedTimeOutput); - itemModifiedDate = systemModifiedTimeOutput.ToDateTime(); - - FileTimeToSystemTime(in findData.ftCreationTime, out SYSTEMTIME systemCreatedTimeOutput); - itemCreatedDate = systemCreatedTimeOutput.ToDateTime(); - } - catch (ArgumentException) - { - } - - var isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden); - var opacity = isHidden ? Constants.UI.DimItemOpacity : 1d; - - var currentFolder = library ?? new ListedItem(null) - { - PrimaryItemAttribute = StorageItemTypes.Folder, - ItemPropertiesInitialized = true, - ItemNameRaw = rootFolder?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\')), - ItemDateModifiedReal = itemModifiedDate, - ItemDateCreatedReal = itemCreatedDate, - ItemType = folderTypeTextLocalized, - FileImage = null, - IsHiddenItem = isHidden, - Opacity = opacity, - LoadFileIcon = false, - ItemPath = path, - FileSize = null, - FileSizeBytes = 0, - }; - - CurrentFolder = currentFolder; - - if (hFile is null) - { - ShowLocationUnavailable(LocationUnavailableKind.DriveUnplugged); - - return -1; - } - else if (hFile.IsInvalid) - { - hFile.Dispose(); - await EnumFromStorageFolderAsync(path, rootFolder, currentStorageFolder, cancellationToken); - - // errorCode == ERROR_ACCESS_DENIED - if (filesAndFolders.Count == 0 && errorCode == 0x5) - { - ShowLocationInaccessibleOrMissing(path); - - return -1; - } - - return 1; - } - else - { - await Task.Run(async () => - { - List fileList = await Win32StorageEnumerator.ListEntries(path, hFile, findData, cancellationToken, -1, GetPreloadIconSize(), intermediateAction: async (intermediateList) => - { - filesAndFolders.AddRange(intermediateList); - - // The stable sort lands new items in final position without reordering visible ones; capped for huge listings - if (filesAndFolders.Count <= 10_000) - await OrderFilesAndFoldersAsync(); - - await ApplyFilesAndFoldersChangesAsync(); - }); - - filesAndFolders.AddRange(fileList); - - await OrderFilesAndFoldersAsync(); - await ApplyFilesAndFoldersChangesAsync(); - // Not awaited here: with Low priority these don't run until the UI thread goes idle - // after the final list update, which would delay load completion and watcher setup. - // The desktop.ini task is awaited before applying the adaptive layout, which reads DesktopIni. - _ = dispatcherQueue.EnqueueOrInvokeAsync(CheckForSolutionFile, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); - desktopIniUpdateTask = dispatcherQueue.EnqueueOrInvokeAsync(() => - { - GetDesktopIniFileData(); - CheckForBackgroundImage(); - }, - Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); - }); - - // Cache the resolved folder so the post-enum switch reuses it. - currentStorageFolder ??= await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path)); - rootFolder ??= currentStorageFolder?.Item; - if (rootFolder is not null) - { - if (rootFolder.DisplayName is not null) - currentFolder.ItemNameRaw = rootFolder.DisplayName; - - if (!string.Equals(path, Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - { - enumeratedCloudSyncStatus = await CheckCloudDriveSyncStatusAsync(rootFolder); - currentFolder.SyncStatusUI = CloudDriveSyncStatusUI.FromCloudDriveSyncStatus(enumeratedCloudSyncStatus.Value); - } - } - - return 0; - } - } - } - - private async Task EnumFromStorageFolderAsync(string path, BaseStorageFolder? rootFolder, StorageFolderWithPath? currentStorageFolder, CancellationToken cancellationToken) - { - if (rootFolder is null) - return; - - // Null when a concurrent navigation or dispose cleared the context; this enumeration is stale - if (currentStorageFolder is null) - return; - - if (rootFolder is IPasswordProtectedItem ppis) - ppis.PasswordRequestedCallback = async (item) => - { - await dispatcherQueue.EnqueueOrInvokeAsync(() => ShowLocationUnavailable(LocationUnavailableKind.PasswordRequired)); - - return await UIFilesystemHelpers.RequestPassword(item); - }; - - try - { - await Task.Run(async () => - { - List finalList = await UniversalStorageEnumerator.ListEntries( - rootFolder, - currentStorageFolder, - cancellationToken, - -1, - GetPreloadIconSize(), - async (intermediateList) => - { - filesAndFolders.AddRange(intermediateList); - - // The stable sort lands new items in final position without reordering visible ones; capped for huge listings - if (filesAndFolders.Count <= 10_000) - await OrderFilesAndFoldersAsync(); - - await ApplyFilesAndFoldersChangesAsync(); - }); - - filesAndFolders.AddRange(finalList); - - await OrderFilesAndFoldersAsync(); - await ApplyFilesAndFoldersChangesAsync(); - }, cancellationToken); - - IsLocationUnavailable = false; - } - catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) // Password dialog dismissed - { - ShowLocationUnavailable(LocationUnavailableKind.PasswordRequired); - } - - if (rootFolder is IPasswordProtectedItem ppiu) - ppiu.PasswordRequestedCallback = null; - } - - private async Task WatchForStorageFolderChangesAsync(BaseStorageFolder? rootFolder) - { - if (rootFolder is null) - return; - - await Task.Run(() => - { - var options = new QueryOptions() - { - FolderDepth = FolderDepth.Shallow, - IndexerOption = IndexerOption.OnlyUseIndexerAndOptimizeForIndexedProperties - }; - - options.SetPropertyPrefetch(PropertyPrefetchOptions.None, null); - options.SetThumbnailPrefetch(ThumbnailMode.ListView, 0, ThumbnailOptions.ReturnOnlyIfCached); - - if (rootFolder.AreQueryOptionsSupported(options)) - { - var itemQueryResult = rootFolder.CreateItemQueryWithOptions(options).ToStorageItemQueryResult() - ?? throw new InvalidOperationException("The folder query could not be converted to a storage query."); - - itemQueryResult.ContentsChanged += ItemQueryResult_ContentsChanged; - - // Just get one item to start getting notifications - var watchedItemsOperation = itemQueryResult.GetItemsAsync(0, 1); - - watcherCTS.Token.Register(() => - { - itemQueryResult.ContentsChanged -= ItemQueryResult_ContentsChanged; - watchedItemsOperation?.Cancel(); - }); - } - }); - } - - private void WatchForWin32FolderChanges(string? folderPath) - { - if (!Directory.Exists(folderPath)) - return; - - // NOTE: Suppressed NullReferenceException caused by EnableRaisingEvents - SafetyExtensions.IgnoreExceptions(() => - { - watcher = new FileSystemWatcher - { - Path = folderPath, - Filter = "*.*", - NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName - }; - - watcher.Created += DirectoryWatcher_Changed; - watcher.Deleted += DirectoryWatcher_Changed; - watcher.Renamed += DirectoryWatcher_Changed; - watcher.EnableRaisingEvents = true; - }, App.Logger); - } - - private async void DirectoryWatcher_Changed(object sender, FileSystemEventArgs e) - { - Debug.WriteLine($"Directory watcher event: {e.ChangeType}, {e.FullPath}"); - - await dispatcherQueue.EnqueueOrInvokeAsync(() => - { - RefreshItems(null); - }); - } - - private async void ItemQueryResult_ContentsChanged(IStorageQueryResultBase sender, object args) - { - // Query options have to be reapplied otherwise old results are returned - var options = new QueryOptions() - { - FolderDepth = FolderDepth.Shallow, - IndexerOption = IndexerOption.OnlyUseIndexerAndOptimizeForIndexedProperties - }; - - options.SetPropertyPrefetch(PropertyPrefetchOptions.None, null); - options.SetThumbnailPrefetch(ThumbnailMode.ListView, 0, ThumbnailOptions.ReturnOnlyIfCached); - - sender.ApplyNewQueryOptions(options); - - await dispatcherQueue.EnqueueOrInvokeAsync(() => - { - RefreshItems(null); - }); - } - - private void WatchForDirectoryChanges(string path, CloudDriveSyncStatus syncStatus) - { - // Enumeration is fire-and-forget; don't set up a watcher on a disposed view model. - if (isDisposed) - return; - - Debug.WriteLine($"WatchForDirectoryChanges: {path}"); - var hWatchDir = Win32PInvoke.CreateFileFromApp(path, 1, 1 | 2 | 4, - IntPtr.Zero, 3, (uint)Win32PInvoke.File_Attributes.BackupSemantics | (uint)Win32PInvoke.File_Attributes.Overlapped, IntPtr.Zero); - if (hWatchDir.ToInt64() == -1) - return; - - var hasSyncStatus = syncStatus != CloudDriveSyncStatus.NotSynced && syncStatus != CloudDriveSyncStatus.Unknown; - - aProcessQueueAction ??= Task.Run(() => ProcessOperationQueueAsync(watcherCTS.Token, hasSyncStatus)); - - var aWatcherAction = Windows.System.Threading.ThreadPool.RunAsync((x) => - { - var buff = new byte[4096]; - var rand = Guid.NewGuid(); - var notifyFilters = FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE; - - if (hasSyncStatus) - notifyFilters |= FILE_NOTIFY_CHANGE_ATTRIBUTES; - - var overlapped = new NativeOverlapped(); - using var eventHandle = PInvoke.CreateEvent(null, false, false, null); - overlapped.EventHandle = eventHandle.DangerousGetHandle(); - const uint INFINITE = 0xFFFFFFFF; - - while (x.Status != AsyncStatus.Canceled) - { - unsafe - { - fixed (byte* pBuff = buff) - { - ref var notifyInformation = ref Unsafe.As(ref buff[0]); - if (x.Status != AsyncStatus.Canceled) - { - PInvoke.ReadDirectoryChanges( - new Windows.Win32.Foundation.HANDLE(hWatchDir), - pBuff, - 4096, - false, - (Windows.Win32.Storage.FileSystem.FILE_NOTIFY_CHANGE)notifyFilters, - null, - &overlapped, - null); - } - else - { - break; - } - - Debug.WriteLine("waiting: {0}", rand); - if (x.Status == AsyncStatus.Canceled) - break; - - var rc = WaitForSingleObjectEx(overlapped.EventHandle, INFINITE, true); - Debug.WriteLine("wait done: {0}", rand); - - uint offset = 0; - ref var notifyInfo = ref Unsafe.As(ref buff[offset]); - if (x.Status == AsyncStatus.Canceled) - break; - - do - { - notifyInfo = ref Unsafe.As(ref buff[offset]); - string? FileName = null; - unsafe - { - fixed (char* name = notifyInfo.FileName) - { - FileName = Path.Combine(path, new string(name, 0, (int)notifyInfo.FileNameLength / 2)); - } - } - - uint action = notifyInfo.Action; - - Debug.WriteLine("action: {0}", action); - - operationQueue.Enqueue((action, FileName)); - - offset += notifyInfo.NextEntryOffset; - } - while (notifyInfo.NextEntryOffset != 0 && x.Status != AsyncStatus.Canceled); - - operationEvent.Set(); - - //ResetEvent(overlapped.hEvent); - Debug.WriteLine("Task running..."); - } - } - } - - operationQueue.Clear(); - - Debug.WriteLine("aWatcherAction done: {0}", rand); - }); - - watcherCTS.Token.Register(() => - { - if (aWatcherAction is not null) - { - aWatcherAction?.Cancel(); - - // Prevent duplicate execution of this block - aWatcherAction = null; - - Debug.WriteLine("watcher canceled"); - } - - CancelIoEx(hWatchDir, IntPtr.Zero); - CloseHandle(hWatchDir); - }); - } - - private void WatchForGitChanges() - { - // Enumeration is fire-and-forget; don't set up a watcher on a disposed view model. - if (isDisposed) - return; - - var hWatchDir = Win32PInvoke.CreateFileFromApp( - GitDirectory!, - 1, - 1 | 2 | 4, - IntPtr.Zero, - 3, - (uint)Win32PInvoke.File_Attributes.BackupSemantics | (uint)Win32PInvoke.File_Attributes.Overlapped, - IntPtr.Zero); - - if (hWatchDir.ToInt64() == -1) - return; - - gitProcessQueueAction ??= Task.Run(() => ProcessGitChangesQueueAsync(watcherCTS.Token)); - - var gitWatcherAction = Windows.System.Threading.ThreadPool.RunAsync((x) => - { - var buff = new byte[4096]; - var rand = Guid.NewGuid(); - var notifyFilters = FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_CREATION; - - var overlapped = new NativeOverlapped(); - using var eventHandle = PInvoke.CreateEvent(null, false, false, null); - overlapped.EventHandle = eventHandle.DangerousGetHandle(); - const uint INFINITE = 0xFFFFFFFF; - - while (x.Status != AsyncStatus.Canceled) - { - unsafe - { - fixed (byte* pBuff = buff) - { - ref var notifyInformation = ref Unsafe.As(ref buff[0]); - if (x.Status == AsyncStatus.Canceled) - break; - - PInvoke.ReadDirectoryChanges( - new Windows.Win32.Foundation.HANDLE(hWatchDir), - pBuff, - 4096, - true, - (Windows.Win32.Storage.FileSystem.FILE_NOTIFY_CHANGE)notifyFilters, - null, - &overlapped, - null); - - if (x.Status == AsyncStatus.Canceled) - break; - - var rc = WaitForSingleObjectEx(overlapped.EventHandle, INFINITE, true); - - uint offset = 0; - ref var notifyInfo = ref Unsafe.As(ref buff[offset]); - if (x.Status == AsyncStatus.Canceled) - break; - - do - { - notifyInfo = ref Unsafe.As(ref buff[offset]); - - uint action = notifyInfo.Action; - - gitChangesQueue.Enqueue(action); - - offset += notifyInfo.NextEntryOffset; - } - while (notifyInfo.NextEntryOffset != 0 && x.Status != AsyncStatus.Canceled); - - gitChangedEvent.Set(); - } - } - } - - gitChangesQueue.Clear(); - }); - - watcherCTS.Token.Register(() => - { - if (gitWatcherAction is not null) - { - gitWatcherAction?.Cancel(); - - // Prevent duplicate execution of this block - gitWatcherAction = null; - } - - CancelIoEx(hWatchDir, IntPtr.Zero); - CloseHandle(hWatchDir); - }); - } - - private async Task ProcessGitChangesQueueAsync(CancellationToken cancellationToken) - { - const int DELAY = 200; - var sampler = new IntervalSampler(100); - int changes = 0; - - try - { - while (!cancellationToken.IsCancellationRequested) - { - if (await gitChangedEvent.WaitAsync(DELAY, cancellationToken)) - { - gitChangedEvent.Reset(); - while (gitChangesQueue.TryDequeue(out var _)) - ++changes; - - if (changes != 0 && sampler.CheckNow()) - { - await dispatcherQueue.EnqueueOrInvokeAsync(() => GitDirectoryUpdated?.Invoke(null, null!)); - changes = 0; - } - } - } - } - catch { } - } - - private async Task ProcessOperationQueueAsync(CancellationToken cancellationToken, bool hasSyncStatus) - { - const uint FILE_ACTION_ADDED = 0x00000001; - const uint FILE_ACTION_REMOVED = 0x00000002; - const uint FILE_ACTION_MODIFIED = 0x00000003; - const uint FILE_ACTION_RENAMED_OLD_NAME = 0x00000004; - const uint FILE_ACTION_RENAMED_NEW_NAME = 0x00000005; - - const int UPDATE_BATCH_SIZE = 32; - var sampler = new IntervalSampler(200); - var updateQueue = new Queue(); - - var anyEdits = false; - ListedItem? lastItemAdded = null; - var rand = Guid.NewGuid(); - - // Call when any edits have occurred - async Task HandleChangesOccurredAsync() - { - await OrderFilesAndFoldersAsync(); - await ApplyFilesAndFoldersChangesAsync(); - - if (lastItemAdded is not null) - { - await RequestSelectionAsync([lastItemAdded]); - lastItemAdded = null; - } - - anyEdits = false; - } - - try - { - while (!cancellationToken.IsCancellationRequested) - { - if (await operationEvent.WaitAsync(200, cancellationToken)) - { - operationEvent.Reset(); - - while (operationQueue.TryDequeue(out var operation)) - { - if (cancellationToken.IsCancellationRequested) - break; - - try - { - switch (operation.Action) - { - case FILE_ACTION_ADDED: - case FILE_ACTION_RENAMED_NEW_NAME: - lastItemAdded = await AddFileOrFolderAsync(operation.FileName); - if (lastItemAdded is not null) - anyEdits = true; - break; - - case FILE_ACTION_MODIFIED: - if (!updateQueue.Contains(operation.FileName)) - updateQueue.Enqueue(operation.FileName); - break; - - case FILE_ACTION_REMOVED: - var itemRemoved = await RemoveFileOrFolderAsync(operation.FileName); - if (itemRemoved is not null) - anyEdits = true; - break; - - case FILE_ACTION_RENAMED_OLD_NAME: - // Pair OLD_NAME with the following NEW_NAME so the item can be updated - // in place and stay at its current position instead of jumping to a new - // sorted slot after a rename (issue #4214). Leaving anyEdits false skips - // OrderFilesAndFoldersAsync; PropertyChanged keeps the visible name in sync. - if (operationQueue.TryPeek(out var nextOp) && nextOp.Action == FILE_ACTION_RENAMED_NEW_NAME && - filesAndFolders.ToList().FirstOrDefault(x => x.GetRequiredPath().Equals(operation.FileName, StringComparison.OrdinalIgnoreCase)) is { } renamed) - { - operationQueue.TryDequeue(out _); - var newPath = nextOp.FileName; - await dispatcherQueue.EnqueueOrInvokeAsync(() => - { - renamed.ItemPath = newPath; - renamed.ItemNameRaw = Path.GetFileName(newPath); - if (renamed.PrimaryItemAttribute == StorageItemTypes.File) - renamed.FileExtension = Path.GetExtension(newPath); - }); - } - else - { - var itemRenamedOld = await RemoveFileOrFolderAsync(operation.FileName); - if (itemRenamedOld is not null) - anyEdits = true; - } - break; - } - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - - if (anyEdits && sampler.CheckNow()) - await HandleChangesOccurredAsync(); - } - - var itemsToUpdate = new List(); - for (var i = 0; i < UPDATE_BATCH_SIZE && updateQueue.Count > 0; i++) - itemsToUpdate.Add(updateQueue.Dequeue()); - - await UpdateFilesOrFoldersAsync(itemsToUpdate, hasSyncStatus); - } - - if (updateQueue.Count > 0) - { - var itemsToUpdate = new List(); - for (var i = 0; i < UPDATE_BATCH_SIZE && updateQueue.Count > 0; i++) - itemsToUpdate.Add(updateQueue.Dequeue()); - - await UpdateFilesOrFoldersAsync(itemsToUpdate, hasSyncStatus); - } - - if (anyEdits && sampler.CheckNow()) - await HandleChangesOccurredAsync(); - } - } - catch - { - // Prevent disposed cancellation token - } - - Debug.WriteLine("aProcessQueueAction done: {0}", rand); - } - - public Task AddFileOrFolderFromShellFile(ShellFileItem item) - { - return - item.IsFolder ? - UniversalStorageEnumerator.AddFolderAsync(ShellStorageFolder.FromShellItem(item), currentStorageFolder, addFilesCTS.Token) : - UniversalStorageEnumerator.AddFileAsync(ShellStorageFile.FromShellItem(item), currentStorageFolder, addFilesCTS.Token); - } - - partial void AddAlternateStreamItems(ListedItem item) - { - if (UserSettingsService.FoldersSettingsService.AreAlternateStreamsVisible) - { - // New file added, enumerate ADS - foreach (var ads in Win32Helper.GetAlternateStreams(item.GetRequiredPath())) - { - var adsItem = Win32StorageEnumerator.GetAlternateStream(ads, item); - filesAndFolders.Add(adsItem); - } - } - } - - private async Task AddFileOrFolderAsync(string fileOrFolderPath) - { - FINDEX_INFO_LEVELS findInfoLevel = FINDEX_INFO_LEVELS.FindExInfoBasic; - var additionalFlags = FIND_FIRST_EX_CASE_SENSITIVE; - - IntPtr hFile = FindFirstFileExFromApp(fileOrFolderPath, findInfoLevel, out WIN32_FIND_DATA findData, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, - additionalFlags); - if (hFile.ToInt64() == -1) - { - // If we cannot find the file (probably since it doesn't exist anymore) simply exit without adding it - return null; - } - - FindClose(hFile); - - var isSystem = ((FileAttributes)findData.dwFileAttributes & FileAttributes.System) == FileAttributes.System; - var isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - var startWithDot = findData.cFileName.StartsWith('.'); - if ((isHidden && - (!UserSettingsService.FoldersSettingsService.ShowHiddenItems || - (isSystem && !UserSettingsService.FoldersSettingsService.ShowProtectedSystemFiles))) || - (startWithDot && !UserSettingsService.FoldersSettingsService.ShowDotFiles)) - { - // Do not add to file list if hidden/system attribute is set and system/hidden file are not to be shown - return null; - } - - var parentPath = Directory.GetParent(fileOrFolderPath)?.FullName - ?? throw new InvalidOperationException("The added item does not have a parent directory."); - - ListedItem? listedItem; - - // FILE_ATTRIBUTE_DIRECTORY - if ((findData.dwFileAttributes & 0x10) > 0) - listedItem = await Win32StorageEnumerator.GetFolder(findData, parentPath, IsValidGitDirectory, addFilesCTS.Token); - else - listedItem = await Win32StorageEnumerator.GetFile(findData, parentPath, IsValidGitDirectory, addFilesCTS.Token); - - if (listedItem is null) - return null; - - await AddFileOrFolderAsync(listedItem); - - return listedItem; - } - } -} diff --git a/src/Files.App/ViewModels/ShellViewModel.cs b/src/Files.App/ViewModels/ShellViewModel.cs index bf96f1c038c4..c0bae3eff12c 100644 --- a/src/Files.App/ViewModels/ShellViewModel.cs +++ b/src/Files.App/ViewModels/ShellViewModel.cs @@ -755,11 +755,6 @@ public ShellViewModel(LayoutPreferencesManager folderSettingsViewModel) fileTagsSettingsService.OnTagsUpdated += FileTagsSettingsService_OnSettingUpdated; folderSizeProvider.SizeChanged += FolderSizeProvider_SizeChanged; folderSettings.LayoutModeChangeRequested += LayoutModeChangeRequested; -#if WINDOWS - StorageTrashBinService.Watcher.ItemAdded += RecycleBinItemCreatedAsync; - StorageTrashBinService.Watcher.ItemDeleted += RecycleBinItemDeletedAsync; - StorageTrashBinService.Watcher.RefreshRequested += RecycleBinRefreshRequestedAsync; -#endif } private async void LayoutModeChangeRequested(object? sender, LayoutModeEventArgs e) @@ -1100,7 +1095,6 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => pendingSearchResults.Clear(); -#if !WINDOWS // A few watcher changes must not rebuild (and visibly blank) the whole list if (TryApplyIncrementalDisplayChanges(displayedFilesAndFolders)) { @@ -1109,7 +1103,6 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => DirectoryInfoUpdated?.Invoke(this, EventArgs.Empty); return; } -#endif FilesAndFolders.BeginBulkOperation(); try @@ -1577,20 +1570,9 @@ private static bool HasPerFileIcon(string? extension) private static Task ReadFileTagAsync(string filePath) { -#if WINDOWS - return Task.Run(() => FileTagsHelper.ReadFileTag(filePath)); -#else return FileTagsHelper.ReadAndUpdateFileTagsAsync(filePath); -#endif } -#if WINDOWS - private static void SetFileTag(ListedItem item) - { - var dbInstance = FileTagsHelper.GetDbInstance(); - dbInstance.SetTags(item.GetRequiredPath(), item.FileFRN, item.FileTags ?? []); - } -#endif // Loads extended file properties off the critical path so a slow per-file read never blocks the row's essentials. private async Task LoadExtendedFilePropertiesInBackgroundAsync(ListedItem item, BaseStorageFile file, CancellationToken token) @@ -1748,9 +1730,6 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => }, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); -#if WINDOWS - await Task.Run(() => SetFileTag(item)); -#endif if (isItemNetwork) _ = LoadExtendedFilePropertiesInBackgroundAsync(item, matchingStorageFile, token); @@ -1815,9 +1794,6 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => }, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); -#if WINDOWS - await Task.Run(() => SetFileTag(item)); -#endif wasSyncStatusLoaded = true; } } @@ -1848,9 +1824,6 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() => }, Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); -#if WINDOWS - await Task.Run(() => SetFileTag(item)); -#endif }); } else @@ -2159,9 +2132,6 @@ private async Task RapidAddItemsToCollectionAsync(string? path, LibraryItem? lib var isRecycleBin = path.StartsWith(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.Ordinal); var addFilesToken = addFilesCTS.Token; -#if WINDOWS - var enumerated = await EnumerateItemsFromStandardFolderAsync(path, addFilesToken, library); -#else int enumerated; try { enumerated = await EnumerateItemsFromStandardFolderAsync(path, addFilesToken, library); } catch (OperationCanceledException) { enumerated = -1; } @@ -2169,47 +2139,12 @@ private async Task RapidAddItemsToCollectionAsync(string? path, LibraryItem? lib // Abandoned requests must not register watchers for a location we've navigated away from if (addFilesToken.IsCancellationRequested) enumerated = -1; -#endif // Hide progressbar after enumeration IsLoadingItems = false; switch (enumerated) { -#if WINDOWS - // Enumerated with FindFirstFileExFromApp - // Is folder synced to cloud storage? - case 0: - currentStorageFolder ??= await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path)); - var syncStatus = enumeratedCloudSyncStatus ?? await CheckCloudDriveSyncStatusAsync(currentStorageFolder?.Item); - - PageTypeUpdated?.Invoke(this, new PageTypeUpdatedEventArgs() - { - IsTypeCloudDrive = syncStatus != CloudDriveSyncStatus.NotSynced && syncStatus != CloudDriveSyncStatus.Unknown, - IsTypeGitRepository = IsValidGitDirectory - }); - - if (!HasNoWatcher) - WatchForDirectoryChanges(path, syncStatus); - if (IsValidGitDirectory) - WatchForGitChanges(); - break; - - // Enumerated with StorageFolder - case 1: - PageTypeUpdated?.Invoke(this, new PageTypeUpdatedEventArgs() { IsTypeCloudDrive = false, IsTypeRecycleBin = isRecycleBin }); - currentStorageFolder ??= await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path)); - if (!HasNoWatcher) - _ = WatchForStorageFolderChangesAsync(currentStorageFolder?.Item); - break; - - // Watch for changes using Win32 in Box Drive folder (#7428) and network drives (#5869) - case 2: - PageTypeUpdated?.Invoke(this, new PageTypeUpdatedEventArgs() { IsTypeCloudDrive = false }); - if (!HasNoWatcher) - WatchForWin32FolderChanges(path); - break; -#endif // Enumerated through IFileSystemEnumerator (Linux) case 3: @@ -2255,9 +2190,7 @@ public void CloseWatcher() watcher?.Dispose(); watcher = null; -#if !WINDOWS CloseLinuxWatcher(); -#endif aProcessQueueAction = null; gitProcessQueueAction = null; @@ -2269,11 +2202,7 @@ private async Task EnumerateItemsFromStandardFolderAsync(string path, Cance { enumeratedCloudSyncStatus = null; -#if WINDOWS - return await EnumerateWindowsFolderAsync(path, cancellationToken, library); -#else return await EnumerateLinuxFolderAsync(path, cancellationToken, library); -#endif } private void CheckForSolutionFile() @@ -2770,11 +2699,6 @@ public void Dispose() updateTagGroupCTS?.Cancel(); App.Logger.LogInformation($"ShellViewModel.Dispose: CurrentFolder={LogPathHelper.RedactPath(CurrentFolder?.ItemPath)}"); -#if WINDOWS - StorageTrashBinService.Watcher.ItemAdded -= RecycleBinItemCreatedAsync; - StorageTrashBinService.Watcher.ItemDeleted -= RecycleBinItemDeletedAsync; - StorageTrashBinService.Watcher.RefreshRequested -= RecycleBinRefreshRequestedAsync; -#endif UserSettingsService.OnSettingChangedEvent -= UserSettingsService_OnSettingChangedEvent; fileTagsSettingsService.OnSettingImportedEvent -= FileTagsSettingsService_OnSettingUpdated; fileTagsSettingsService.OnTagsUpdated -= FileTagsSettingsService_OnSettingUpdated; diff --git a/src/Files.App/ViewModels/UserControls/InfoPaneViewModel.cs b/src/Files.App/ViewModels/UserControls/InfoPaneViewModel.cs index 5b7d2a0401f8..d4a74ea7bb90 100644 --- a/src/Files.App/ViewModels/UserControls/InfoPaneViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/InfoPaneViewModel.cs @@ -276,15 +276,6 @@ private async Task LoadPreviewControlAsync(CancellationToken token, bool downloa return new BasicPreview(model); } -#if WINDOWS - if (FileExtensionHelpers.IsBrowsableZipFile(item.FileExtension, out _)) - { - var model = new ArchivePreviewViewModel(item); - await model.LoadAsync(); - - return new BasicPreview(model); - } -#endif #if DESKTOP if (item.PrimaryItemAttribute != StorageItemTypes.Folder && !item.IsFtpItem && ArchiveListingPreview.IsArchive(item)) @@ -337,16 +328,6 @@ private async Task LoadPreviewControlAsync(CancellationToken token, bool downloa #endif } -#if WINDOWS - if (FileExtensionHelpers.IsMarkdownFile(ext)) - { - var model = new MarkdownPreviewViewModel(item); - await model.LoadAsync(); - - return new MarkdownPreview(model); - } - -#else // Markdown and highlighted code render as inert text with Markdig / ColorCode.Core; HTML is shown as source, never rendered. // LINUX-TODO(preview): shell scripts and other languages without a ColorCode grammar are shown as plain text if (FileExtensionHelpers.IsMarkdownFile(ext) && @@ -357,7 +338,6 @@ await TextPreviewViewModel.TryLoadWithKindAsync(item, TextPreviewKind.Markdown, await TextPreviewViewModel.TryLoadWithKindAsync(item, TextPreviewKind.Code, codeLanguage, token) is { } codePreview) return codePreview; -#endif if (FileExtensionHelpers.IsImagePreviewFile(ext) #if DESKTOP || FileExtensionHelpers.IsPdfFile(ext) @@ -402,43 +382,7 @@ await TextPreviewViewModel.TryLoadWithKindAsync(item, TextPreviewKind.Code, code }*/ // LINUX-TODO(preview): implement an RTF renderer for desktop. -#if WINDOWS - if (FileExtensionHelpers.IsRichTextFile(ext)) - { - var model = new RichTextPreviewViewModel(item); - await model.LoadAsync(); - - return new RichTextPreview(model); - } - -#endif -#if WINDOWS - if (CodePreviewViewModel.IsCodeFile(ext)) - { - var model = new CodePreviewViewModel(item); - await model.LoadAsync(); - - return new CodePreview(model); - } - -#endif -#if WINDOWS - if (ShellPreviewViewModel.FindPreviewHandlerFor(item.FileExtension, 0) is not null && - !FileExtensionHelpers.IsFontFile(item.FileExtension) && - !FileExtensionHelpers.IsExecutableFile(item.FileExtension)) - { - var model = new ShellPreviewViewModel(item); - await model.LoadAsync(); - - return new ShellPreview(model); - } - -#endif -#if WINDOWS - var control = await TextPreviewViewModel.TryLoadAsTextAsync(item); -#else var control = await TextPreviewViewModel.TryLoadAsTextAsync(item, token); -#endif return control ?? null; } @@ -609,10 +553,6 @@ public void UnloadPreview() CancelPreviewLoad(); // Tear the preview host down here since the control's Unloaded event won't reliably fire while we're closing to background -#if WINDOWS - if (previewPaneContent is ShellPreview shellPreview) - shellPreview.UnloadPreview(); -#endif PreviewPaneContent = null; } diff --git a/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.Windows.cs deleted file mode 100644 index 7e6304367e39..000000000000 --- a/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.Windows.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.Shared.Helpers; -using System.IO; -using Windows.Win32; -using Windows.Win32.Storage.FileSystem; - -namespace Files.App.ViewModels.UserControls -{ - public sealed partial class NavigationToolbarViewModel - { - /// - /// Enumerates subfolders using Win32 API, including hidden folders based on user settings. - /// Returns null if the path cannot be enumerated with Win32. - /// - private unsafe List<(string Name, string Path, bool IsHidden)>? GetSubfolders(string parentPath) - { - WIN32_FIND_DATAW findData = default; - using FindCloseSafeHandle hFile = PInvoke.FindFirstFileEx( - $"{parentPath}{Path.DirectorySeparatorChar}*.*", - FINDEX_INFO_LEVELS.FindExInfoBasic, - &findData, - FINDEX_SEARCH_OPS.FindExSearchNameMatch, - FIND_FIRST_EX_FLAGS.FIND_FIRST_EX_LARGE_FETCH); - - if (hFile.IsInvalid) - return null; - - var showHidden = UserSettingsService.FoldersSettingsService.ShowHiddenItems; - var showSystem = UserSettingsService.FoldersSettingsService.ShowProtectedSystemFiles; - var showDot = UserSettingsService.FoldersSettingsService.ShowDotFiles; - var folders = new List<(string Name, string Path, bool IsHidden)>(); - - do - { - if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == 0) - continue; - - string fileName = findData.cFileName.ToString(); - if (fileName is "." or "..") - continue; - - bool isHidden = ((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) != 0; - bool isSystem = ((FileAttributes)findData.dwFileAttributes & FileAttributes.System) != 0; - - if (isHidden && (!showHidden || (isSystem && !showSystem))) - continue; - - if (fileName.StartsWith('.') && !showDot) - continue; - - folders.Add((fileName, Path.Combine(parentPath, fileName), isHidden)); - } - while (PInvoke.FindNextFile(hFile, out findData)); - - var naturalComparer = NaturalStringComparer.GetForProcessor(); - folders.Sort((a, b) => naturalComparer.Compare(a.Name, b.Name)); - - return folders; - } - } -} diff --git a/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs b/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs index 62827f4d626f..8d719bf9e456 100644 --- a/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/NavigationToolbarViewModel.cs @@ -675,11 +675,7 @@ public async Task HandleItemNavigationAsync(string path) { var storageFile = resFile.Result ?? throw new InvalidOperationException("A successful file lookup did not return a storage file."); -#if !WINDOWS await NavigationHelpers.OpenPath(storageFile.Path, shellPage, FilesystemItemType.File); -#else - await Win32Helper.InvokeWin32ComponentAsync(storageFile.Path, shellPage); -#endif } else // Not a file or not accessible { @@ -763,11 +759,7 @@ public async Task SetPathBoxDropDownFlyoutAsync(MenuFlyout flyout, PathBoxItem p var path = pathItem.Path ?? throw new InvalidOperationException("The path box item does not have a path."); -#if WINDOWS - var childFolders = OperatingSystem.IsWindows() ? GetSubfolders(path) : await GetSubfoldersAsync(path); -#else var childFolders = await GetSubfoldersAsync(path); -#endif // Fall back to StorageFolder API for non-filesystem paths (e.g. FTP) if (childFolders is null) @@ -999,11 +991,7 @@ await DialogDisplayHelper.ShowDialogAsync(Strings.CommandNotExecutable.GetLocali { var storageFile = resFile.Result ?? throw new InvalidOperationException("A successful file lookup did not return a storage file."); -#if !WINDOWS await NavigationHelpers.OpenPath(storageFile.Path, shellPage, FilesystemItemType.File); -#else - await Win32Helper.InvokeWin32ComponentAsync(storageFile.Path, shellPage); -#endif } else // Not a file or not accessible { @@ -1061,15 +1049,8 @@ public void SaveSearchQueryToList(string searchQuery) private static async Task LaunchApplicationFromPath(string currentInput, string workingDir) { -#if !WINDOWS // LINUX-TODO(launch): running commands typed into the address bar; the input is reported as an invalid path return await Task.FromResult(false); -#else - var args = CommandLineParser.SplitArguments(currentInput); - return await LaunchHelper.LaunchAppAsync( - args.FirstOrDefault("").Trim('"'), string.Join(' ', args.Skip(1)), workingDir - ); -#endif } public async Task PopulateOmnibarSuggestionsForPathMode() diff --git a/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.Windows.cs deleted file mode 100644 index 1b105810bba6..000000000000 --- a/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.Windows.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Properties; -using SevenZip; -using System.IO; - -namespace Files.App.ViewModels.Previews -{ - public sealed partial class ArchivePreviewViewModel : BasePreviewModel - { - public ArchivePreviewViewModel(ListedItem item) - : base(item) - { - } - - public override async Task> LoadPreviewAndDetailsAsync() - { - var details = new List(); - - var zipResult = await FilesystemTasks.WrapNullable(async () => - { - var arch = new SevenZipExtractor(await PreviewFile.OpenStreamForReadAsync()); - - // Force load archive (1665013614u) - if (arch.ArchiveFileData is null) - { - arch.Dispose(); - return null; - } - - return arch; - }); - using var zipFile = zipResult.Result; - - if (zipFile is null) - { - // Loads the thumbnail preview - _ = await base.LoadPreviewAndDetailsAsync(); - - return details; - } - - //zipFile.IsStreamOwner = true; - - var folderCount = 0; - var fileCount = 0; - ulong totalSize = 0; - - foreach (ArchiveFileInfo entry in zipFile.ArchiveFileData) - { - if (!entry.IsDirectory) - { - ++fileCount; - totalSize += entry.Size; - } - } - - folderCount = (int)zipFile.FilesCount - fileCount; - - string propertyItemCount = Strings.DetailsArchiveItems.GetLocalizedFormatResource(zipFile.FilesCount, fileCount, folderCount); - details.Add(GetFileProperty("PropertyItemCount", propertyItemCount)); - details.Add(GetFileProperty("PropertyUncompressedSize", totalSize.ToLongSizeString())); - - // Loads the thumbnail preview - _ = await base.LoadPreviewAndDetailsAsync(); - return details; - } - } -} diff --git a/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.cs index c234a6ddf7ee..7f9329146f37 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/ArchivePreviewViewModel.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Files.App.ViewModels.Properties; using Files.Platform.Abstractions.Archives; @@ -24,4 +23,3 @@ public override async Task> LoadPreviewAndDetailsAsync() } } } -#endif diff --git a/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.Windows.cs deleted file mode 100644 index 67d4fd4c7776..000000000000 --- a/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.Windows.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Properties; -using System.IO; - -namespace Files.App.ViewModels.Previews -{ - public abstract partial class BasePreviewModel - { - private async Task?> GetSystemFilePropertiesAsync() - { - if (Item.IsShortcut) - return null; - if (Item.ItemFile is null) - throw new InvalidOperationException("The preview item could not be opened as a file."); - - var list = await FileProperty.RetrieveAndInitializePropertiesAsync(Item.ItemFile, - Constants.ResourceFilePaths.PreviewPaneDetailsPropertiesJsonPath); - - var address = list.Find(x => x.ID is "address") - ?? throw new InvalidDataException("The preview property definition is missing the address field."); - var latitude = list.Find(x => x.Property is "System.GPS.LatitudeDecimal") - ?? throw new InvalidDataException("The preview property definition is missing the latitude field."); - var longitude = list.Find(x => x.Property is "System.GPS.LongitudeDecimal") - ?? throw new InvalidDataException("The preview property definition is missing the longitude field."); - address.Value = await LocationHelpers.GetAddressFromCoordinatesAsync( - (double?)latitude.Value, - (double?)longitude.Value); - - // Adds the value for the file tag - var fileTag = list.FirstOrDefault(x => x.ID is "filetag") - ?? throw new InvalidDataException("The preview property definition is missing the file tag field."); - fileTag.Value = Item.FileTagsUI is not null - ? string.Join(',', Item.FileTagsUI.Select(x => x.Name)) - : null; - - return list.Where(i => i.ValueText is not null).ToList(); - } - } -} diff --git a/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.cs index 668fb65a300d..e1076150ae78 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/BasePreviewModel.cs @@ -3,9 +3,7 @@ using System.IO; using Files.Core.Storage.Contracts; -#if !WINDOWS using OwlCore.Storage.System.IO; -#endif using Files.App.ViewModels.Properties; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Media.Imaging; @@ -18,11 +16,7 @@ public abstract partial class BasePreviewModel : ObservableObject public ListedItem Item { get; } -#if WINDOWS - protected BaseStorageFile PreviewFile -#else protected IFile PreviewFile -#endif => Item.ItemFile ?? throw new InvalidOperationException("The preview file has not been loaded."); private BitmapImage? fileImage; @@ -50,10 +44,6 @@ public static Task LoadDetailsOnlyAsync(ListedItem item, List? det return temp.LoadAsync(); } -#if WINDOWS - public static Task ReadFileAsTextAsync(BaseStorageFile file, int maxLength = 10 * 1024 * 1024) - => file.ReadTextAsync(maxLength); -#else protected static async Task ResolvePreviewFileAsync(ListedItem item, CancellationToken cancellationToken) { if (item.ItemFile is null) @@ -80,7 +70,6 @@ protected async Task OpenPreviewReadAsync(CancellationToken cancellation ?? throw new IOException("The preview file could not be resolved."); return await OpenPreviewReadAsync(file, cancellationToken); } -#endif /// /// Call this function when you are ready to load the preview and details. @@ -93,13 +82,7 @@ public virtual async Task LoadAsync() if (Item.ItemFile is null) { -#if WINDOWS - var itemPath = Item.ItemPath!; - var rootItem = await FilesystemTasks.WrapNullable(() => DriveHelpers.GetRootFromPathAsync(itemPath)); - Item.ItemFile = await StorageFileExtensions.DangerousGetFileFromPathAsync(itemPath, rootItem.Result); -#else await ResolvePreviewFileAsync(Item, LoadCancelledTokenSource.Token); -#endif } await Task.Run(async () => diff --git a/src/Files.App/ViewModels/UserControls/Previews/CodeLanguageMap.cs b/src/Files.App/ViewModels/UserControls/Previews/CodeLanguageMap.cs index 852887c62c17..66407782c86f 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/CodeLanguageMap.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/CodeLanguageMap.cs @@ -1,4 +1,3 @@ -#if !WINDOWS // Copyright (c) Files Community // Licensed under the MIT License. @@ -55,4 +54,3 @@ private static FrozenDictionary Build() } } -#endif diff --git a/src/Files.App/ViewModels/UserControls/Previews/CodePreviewViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Previews/CodePreviewViewModel.Windows.cs deleted file mode 100644 index 8dbd7c3cb4c4..000000000000 --- a/src/Files.App/ViewModels/UserControls/Previews/CodePreviewViewModel.Windows.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using ColorCode; -using Files.App.ViewModels.Properties; -using System.Collections.Frozen; - -namespace Files.App.ViewModels.Previews -{ - public sealed partial class CodePreviewViewModel : BasePreviewModel - { - private static readonly FrozenDictionary extensions = GetDictionary(); - - private string? textValue; - public string? TextValue - { - get => textValue; - private set => SetProperty(ref textValue, value); - } - - private ILanguage? codeLanguage; - public ILanguage? CodeLanguage - { - get => codeLanguage; - private set => SetProperty(ref codeLanguage, value); - } - - public CodePreviewViewModel(ListedItem item) - : base(item) - { - } - - public static bool IsCodeFile(string extension) - => extensions.ContainsKey(extension); - - public async override Task> LoadPreviewAndDetailsAsync() - { - var details = new List(); - - try - { - var text = TextValue ?? await ReadFileAsTextAsync(PreviewFile); - details.Add(GetFileProperty("PropertyLineCount", text.Split('\n').Length)); - - CodeLanguage = extensions[Item.FileExtension!.ToLowerInvariant()]; - TextValue = text.Left(Constants.PreviewPane.TextCharacterLimit); - } - catch (Exception e) - { - Debug.WriteLine(e); - } - - return details; - } - - private static FrozenDictionary GetDictionary() - { - var items = new Dictionary - { - [Languages.Aspx] = "aspx", - [Languages.AspxCs] = "acsx", - [Languages.Cpp] = "cpp,c++,cc,cp,cxx,h,h++,hh,hpp,hxx,inc,inl,ino,ipp,re,tcc,tpp", - [Languages.CSharp] = "cs,cake,csx,linq", - [Languages.Css] = "css,scss", - [Languages.FSharp] = "fs,fsi,fsx", - [Languages.Haskell] = "hs", - [Languages.Html] = "razor,cshtml,vbhtml,svelte", - [Languages.Java] = "java", - [Languages.JavaScript] = "js,jsx", - [Languages.Php] = "php", - [Languages.PowerShell] = "pwsh,ps1,psd1,psm1", - [Languages.Typescript] = "ts,tsx", - [Languages.VbDotNet] = "vb,vbs", - [Languages.Xml] = "xml,axml,xaml,xsd,xsl,xslt,xlf", - }; - - var dictionary = new Dictionary(); - - foreach (var item in items) - { - var extensions = item.Value.Split(',').Select(ext => $".{ext}"); - foreach (var extension in extensions) - { - dictionary.Add(extension, item.Key); - } - } - - return dictionary.ToFrozenDictionary(); - } - } -} diff --git a/src/Files.App/ViewModels/UserControls/Previews/FolderPreviewViewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/FolderPreviewViewModel.cs index 97555232dbed..b820601e59c2 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/FolderPreviewViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/FolderPreviewViewModel.cs @@ -25,15 +25,9 @@ public Task LoadAsync() private async Task LoadPreviewAndDetailsAsync() { var itemPath = Item.ItemPath!; -#if WINDOWS - var rootItem = await FilesystemTasks.WrapNullable(() => DriveHelpers.GetRootFromPathAsync(itemPath)); - var folder = await StorageFileExtensions.DangerousGetFolderFromPathAsync(itemPath, rootItem.Result) - ?? throw new InvalidOperationException("The preview folder could not be opened."); -#else var resolved = await Ioc.Default.GetRequiredService().TryGetAsync(itemPath); if (resolved.Item is not IFolder) throw new IOException("The preview folder could not be resolved."); -#endif var result = await FileThumbnailHelper.GetIconAsync( Item.ItemPath, @@ -50,15 +44,9 @@ private async Task LoadPreviewAndDetailsAsync() if (Item.IsDriveRoot || infoPaneViewModel?.SelectedDriveItem is not null) return; -#if WINDOWS - var info = await folder.GetBasicPropertiesAsync(); - var dateModified = info.DateModified; - var dateCreated = info.DateCreated; -#else var localInfo = resolved.Item is SystemFolder ? new DirectoryInfo(itemPath) : null; var dateModified = localInfo is null ? Item.ItemDateModifiedReal : new DateTimeOffset(localInfo.LastWriteTime); var dateCreated = localInfo is null ? Item.ItemDateCreatedReal : new DateTimeOffset(localInfo.CreationTime); -#endif Item.FileDetails = [ diff --git a/src/Files.App/ViewModels/UserControls/Previews/MarkdownPreviewViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Previews/MarkdownPreviewViewModel.Windows.cs deleted file mode 100644 index cc53068f87c8..000000000000 --- a/src/Files.App/ViewModels/UserControls/Previews/MarkdownPreviewViewModel.Windows.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Properties; -using System.Text; - -namespace Files.App.ViewModels.Previews -{ - public sealed partial class MarkdownPreviewViewModel : BasePreviewModel - { - private string? textValue; - public string? TextValue - { - get => textValue; - private set => SetProperty(ref textValue, value); - } - - public MarkdownPreviewViewModel(ListedItem item) - : base(item) - { - } - - public override async Task> LoadPreviewAndDetailsAsync() - { - var text = await ReadFileAsTextAsync(PreviewFile); - TextValue = EscapeRawHtml(text.Left(Constants.PreviewPane.TextCharacterLimit)); - - return []; - } - - // Escape raw '<' outside code so Markdig doesn't emit HtmlInline nodes — those crash MarkdownTextBlock's HtmlWriter.WriteHtml. - private static string EscapeRawHtml(string markdown) - { - if (string.IsNullOrEmpty(markdown)) - return markdown; - - var sb = new StringBuilder(markdown.Length); - var inFencedBlock = false; - - var start = 0; - for (var i = 0; i <= markdown.Length; i++) - { - if (i == markdown.Length || markdown[i] == '\n') - { - var lineLen = i - start; - var line = markdown.AsSpan(start, lineLen); - var trimmed = line.TrimStart(); - - if (trimmed.StartsWith("```") || trimmed.StartsWith("~~~")) - { - inFencedBlock = !inFencedBlock; - sb.Append(line); - } - else if (inFencedBlock) - { - sb.Append(line); - } - else - { - AppendLineWithEscapes(sb, line); - } - - if (i < markdown.Length) - sb.Append('\n'); - - start = i + 1; - } - } - - return sb.ToString(); - } - - private static void AppendLineWithEscapes(StringBuilder sb, ReadOnlySpan line) - { - var inInlineCode = false; - for (var j = 0; j < line.Length; j++) - { - var ch = line[j]; - if (ch == '`') - { - inInlineCode = !inInlineCode; - sb.Append(ch); - } - else if (ch == '<' && !inInlineCode) - { - sb.Append("<"); - } - else - { - sb.Append(ch); - } - } - } - } -} diff --git a/src/Files.App/ViewModels/UserControls/Previews/MediaPreviewViewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/MediaPreviewViewModel.cs index 65886767dd1c..988fffb82447 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/MediaPreviewViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/MediaPreviewViewModel.cs @@ -25,14 +25,8 @@ public void TogglePlayback() public override Task> LoadPreviewAndDetailsAsync() { -#if WINDOWS - var itemFile = Item.ItemFile - ?? throw new InvalidOperationException("The media preview item does not have a storage file."); - Source = MediaSource.CreateFromStorageFile(itemFile); -#else // LINUX-TODO(media): desktop shows metadata only (MediaMetadataPreviewViewModel); playback needs libvlc throw new NotSupportedException(); -#endif return Task.FromResult(new List()); } diff --git a/src/Files.App/ViewModels/UserControls/Previews/PDFPreviewViewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/PDFPreviewViewModel.cs index 7e7476874efe..91b09e9c1131 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/PDFPreviewViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/PDFPreviewViewModel.cs @@ -35,23 +35,9 @@ public PDFPreviewViewModel(ListedItem item) public async override Task> LoadPreviewAndDetailsAsync() { -#if !WINDOWS // LINUX-TODO(preview): desktop renders PDFs through ImagePreviewViewModel await Task.CompletedTask; throw new NotSupportedException(); -#else - var fileStream = await PreviewFile.OpenReadAsync(); - var pdf = await PdfDocument.LoadFromStreamAsync(fileStream); - _ = TryLoadPagesAsync(pdf, fileStream); - - var details = new List - { - // Add the number of pages to the details - GetFileProperty("PropertyPageCount", pdf.PageCount) - }; - - return details; -#endif } public async Task TryLoadPagesAsync(PdfDocument pdf, IRandomAccessStream fileStream) diff --git a/src/Files.App/ViewModels/UserControls/Previews/PreviewCodeTokenizer.cs b/src/Files.App/ViewModels/UserControls/Previews/PreviewCodeTokenizer.cs index 13257de32c97..93fcb3764166 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/PreviewCodeTokenizer.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/PreviewCodeTokenizer.cs @@ -1,4 +1,3 @@ -#if !WINDOWS // Copyright (c) Files Community // Licensed under the MIT License. @@ -52,4 +51,3 @@ protected override void Write(string parsedSourceCode, IList scopes) { } } } -#endif diff --git a/src/Files.App/ViewModels/UserControls/Previews/PreviewTextReader.cs b/src/Files.App/ViewModels/UserControls/Previews/PreviewTextReader.cs index a7b2bad192e8..fbf928571680 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/PreviewTextReader.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/PreviewTextReader.cs @@ -1,4 +1,3 @@ -#if !WINDOWS // Copyright (c) Files Community // Licensed under the MIT License. @@ -112,4 +111,3 @@ private static (Encoding Encoding, int BomLength) DetectEncoding(byte[] data, in } } -#endif diff --git a/src/Files.App/ViewModels/UserControls/Previews/RichTextPreviewViewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/RichTextPreviewViewModel.cs index dbc207d826d2..6673facf95d0 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/RichTextPreviewViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/RichTextPreviewViewModel.cs @@ -14,15 +14,9 @@ public RichTextPreviewViewModel(ListedItem item) : base(item) { } public async override Task> LoadPreviewAndDetailsAsync() { -#if WINDOWS - Stream = await PreviewFile.OpenReadAsync(); - - return []; -#else // LINUX-TODO(preview): no RTF renderer on desktop await Task.CompletedTask; throw new NotSupportedException(); -#endif } } } diff --git a/src/Files.App/ViewModels/UserControls/Previews/ShellPreviewViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Previews/ShellPreviewViewModel.Windows.cs deleted file mode 100644 index 74a98e54a7fa..000000000000 --- a/src/Files.App/ViewModels/UserControls/Previews/ShellPreviewViewModel.Windows.cs +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.Helpers; -using Files.App.ViewModels.Properties; -using Microsoft.Extensions.Logging; -using Microsoft.UI.Content; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Hosting; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.Marshalling; -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.Graphics.Direct3D; -using Windows.Win32.Graphics.Direct3D11; -using Windows.Win32.Graphics.DirectComposition; -using Windows.Win32.Graphics.Dwm; -using Windows.Win32.Graphics.Dxgi; -using Windows.Win32.System.Com; -using Windows.Win32.UI.Shell; -using Windows.Win32.UI.WindowsAndMessaging; -using WinRT; -using WNDPROC = Windows.Win32.Extras.ManagedWNDPROC; - -#pragma warning disable CS8305 // Type is for evaluation purposes only and is subject to change or removal in future updates. - -namespace Files.App.ViewModels.Previews -{ - public sealed partial class ShellPreviewViewModel : BasePreviewModel - { - // Fields - - ContentExternalOutputLink? _contentExternalOutputLink; - PreviewHandler? _previewHandler; - ID3D11Device? _d3d11Device; - ID3D11DeviceContext? _d3d11DeviceContext; - IDCompositionDevice? _dCompositionDevice; - IDCompositionVisual? _childVisual; - object? _controlSurface; - WNDCLASSEXW _windowClass; - WNDPROC _windProc = null!; - HWND _hWnd = HWND.Null; - bool _isOfficePreview = false; - bool _unloaded; - unsafe char* _pszClassName; - - // Constructor - - public ShellPreviewViewModel(ListedItem item) : base(item) - { - } - - // Methods - - public override Task> LoadPreviewAndDetailsAsync() - => Task.FromResult>([]); - - public static unsafe Guid? FindPreviewHandlerFor(string extension, nint hwnd) - { - if (string.IsNullOrEmpty(extension)) - return null; - - try - { - fixed (char* pszAssoc = extension, - pszExtra = "{8895b1c6-b41f-4c1c-a562-0d564250836f}", - pszOutput = new char[1024]) - { - PWSTR pwszAssoc = new(pszAssoc); - PWSTR pwszExtra = new(pszExtra); - PWSTR pwszOutput = new(pszOutput); - uint cchOutput = 2024; - - // Try to find registered preview handler associated with specified extension name - var res = PInvoke.AssocQueryString( - ASSOCF.ASSOCF_NOTRUNCATE, - ASSOCSTR.ASSOCSTR_SHELLEXTENSION, - pwszAssoc, - pwszExtra, - pwszOutput, - &cchOutput); - - return Guid.Parse(pwszOutput.ToString()); - } - } - catch - { - return null; - } - } - - public void SizeChanged(RECT size) - { - if (_hWnd != HWND.Null) - PInvoke.SetWindowPos(_hWnd, new(0), size.left, size.top, size.Width, size.Height, SET_WINDOW_POS_FLAGS.SWP_NOACTIVATE); - - _previewHandler?.ResetBounds(new(0, 0, size.Width, size.Height)); - - if (_contentExternalOutputLink is not null) - _contentExternalOutputLink.PlacementVisual.Size = new(size.Width, size.Height); - } - - private unsafe LRESULT WndProc(HWND hwnd, uint msg, WPARAM wParam, LPARAM lParam) - { - if (msg is PInvoke.WM_CREATE) - { - var clsid = FindPreviewHandlerFor(Item.FileExtension!, hwnd); - - _isOfficePreview = new Guid?[] - { - Guid.Parse("84F66100-FF7C-4fb4-B0C0-02CD7FB668FE"), // preview handler for Word files - Guid.Parse("65235197-874B-4A07-BDC5-E65EA825B718"), // preview handler for PowerPoint files - Guid.Parse("00020827-0000-0000-C000-000000000046") // preview handler for Excel files - }.Contains(clsid); - - try - { - _previewHandler = new PreviewHandler(clsid!.Value, hwnd); - _previewHandler.InitWithFileWithEveryWay(Item.ItemPath!); - _previewHandler.DoPreview(); - } - catch - { - UnloadPreview(); - } - } - else if (msg is PInvoke.WM_DESTROY) - { - if (_previewHandler is not null) - { - _previewHandler.Dispose(); - _previewHandler = null; - } - } - - return PInvoke.DefWindowProc(hwnd, msg, wParam, lParam); - } - - public unsafe void LoadPreview(UIElement presenter) - { - App.Logger.LogInformation($"ShellPreview.LoadPreview: Item={LogPathHelper.RedactPath(Item?.ItemPath)}"); - - var parent = MainWindow.Instance.WindowHandle; - var hInst = PInvoke.GetModuleHandle(default(PWSTR)); - var szClassName = $"{nameof(ShellPreviewViewModel)}-{Guid.NewGuid()}"; - var szWindowName = $"Preview"; - - _pszClassName = (char*)Marshal.StringToHGlobalUni(szClassName); - - _windProc = new(WndProc); - var pWindProc = Marshal.GetFunctionPointerForDelegate(_windProc); - var pfnWndProc = (delegate* unmanaged[Stdcall])pWindProc; - - _windowClass = new WNDCLASSEXW() - { - cbSize = (uint)sizeof(WNDCLASSEXW), - lpfnWndProc = pfnWndProc, - hInstance = hInst, - lpszClassName = _pszClassName, - style = 0, - hIcon = default, - hIconSm = default, - hCursor = default, - hbrBackground = default, - lpszMenuName = null, - cbClsExtra = 0, - cbWndExtra = 0, - }; - - PInvoke.RegisterClassEx(_windowClass); - - fixed (char* pszWindowName = szWindowName) - { - _hWnd = PInvoke.CreateWindowEx( - WINDOW_EX_STYLE.WS_EX_LAYERED | WINDOW_EX_STYLE.WS_EX_COMPOSITED, - _pszClassName, - pszWindowName, - WINDOW_STYLE.WS_CHILD | WINDOW_STYLE.WS_CLIPSIBLINGS | WINDOW_STYLE.WS_VISIBLE, - 0, 0, 0, 0, - new(parent), - HMENU.Null, - hInst); - } - - _ = ChildWindowToXaml(parent, presenter); - } - - private unsafe bool ChildWindowToXaml(nint parent, UIElement presenter) - { - D3D_DRIVER_TYPE[] driverTypes = - [ - D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, - D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_WARP, - ]; - - HRESULT hr = default; - - // Create the D3D11 device - foreach (var driverType in driverTypes) - { - hr = PInvoke.D3D11CreateDevice( - null!, driverType, new(nint.Zero), - D3D11_CREATE_DEVICE_FLAG.D3D11_CREATE_DEVICE_BGRA_SUPPORT, - ReadOnlySpan.Empty, /* SDKVersion */ 7, - out _d3d11Device, - out _d3d11DeviceContext); - - if (hr.Succeeded) - break; - } - - if (_d3d11Device is null) - return false; - - // Create the DComp device - var pDXGIDevice = (IDXGIDevice)_d3d11Device; - hr = PInvoke.DCompositionCreateDevice(pDXGIDevice, out _dCompositionDevice); - if (hr.Failed || _dCompositionDevice is null) - return false; - - // Create the visual - hr = _dCompositionDevice.CreateVisual(out _childVisual); - if (hr.Failed) - return false; - - hr = _dCompositionDevice.CreateSurfaceFromHwnd(_hWnd, out _controlSurface); - if (hr.Failed) - return false; - - hr = _childVisual.SetContent(_controlSurface); - if (hr.Failed || _childVisual is null || _controlSurface is null) - return false; - - // Get the compositor and set the visual on it - var compositor = ElementCompositionPreview.GetElementVisual(presenter).Compositor; - _contentExternalOutputLink = ContentExternalOutputLink.Create(compositor); - - var target = _contentExternalOutputLink.As(); - target.SetRoot(_childVisual); - - _contentExternalOutputLink.PlacementVisual.Size = new(0, 0); - _contentExternalOutputLink.PlacementVisual.Scale = new(1 / (float)presenter.XamlRoot.RasterizationScale); - ElementCompositionPreview.SetElementChildVisual(presenter, _contentExternalOutputLink.PlacementVisual); - - // Commit the all pending DComp commands - _dCompositionDevice.Commit(); - - var dwAttrib = Convert.ToUInt32(true); - - return - PInvoke.DwmSetWindowAttribute( - new((nint)_hWnd), - DWMWINDOWATTRIBUTE.DWMWA_CLOAK, - &dwAttrib, - (uint)Marshal.SizeOf(dwAttrib)) - .Succeeded; - } - - public unsafe void UnloadPreview() - { - // Called both when closing to background and from Unloaded, so ignore the second call - if (_unloaded) - return; - _unloaded = true; - - if (_hWnd != HWND.Null) - { - PInvoke.DestroyWindow(_hWnd); - App.Logger.LogInformation($"ShellPreview.UnloadPreview: HWND={((nint)_hWnd)}, Item={LogPathHelper.RedactPath(Item?.ItemPath)}"); - _hWnd = HWND.Null; - } - else - App.Logger.LogInformation($"ShellPreview.UnloadPreview: HWND=, Item={LogPathHelper.RedactPath(Item?.ItemPath)}"); - - - _contentExternalOutputLink?.Dispose(); - _contentExternalOutputLink = null; - - // Release the composition chain leaf-to-root so nothing is left for finalizer-thread teardown - ReleaseComObject(ref _childVisual); - ReleaseComObject(ref _controlSurface); - ReleaseComObject(ref _dCompositionDevice); - ReleaseComObject(ref _d3d11DeviceContext); - ReleaseComObject(ref _d3d11Device); - - PInvoke.UnregisterClass(_windowClass.lpszClassName, PInvoke.GetModuleHandle(default(PWSTR))); - - if (_pszClassName is not null) - { - Marshal.FreeHGlobal((nint)_pszClassName); - _pszClassName = null; - } - } - - private static void ReleaseComObject(ref T? comInterface) where T : class - { - if ((object?)comInterface is ComObject comObject) - comObject.FinalRelease(); - - comInterface = null; - } - - public unsafe void PointerEntered(bool onPreview) - { - if (onPreview) - { - var dwAttrib = Convert.ToUInt32(false); - - PInvoke.DwmSetWindowAttribute( - new((nint)_hWnd), - DWMWINDOWATTRIBUTE.DWMWA_CLOAK, - &dwAttrib, - (uint)Marshal.SizeOf(dwAttrib)); - - if (_isOfficePreview) - PInvoke.SetWindowLongPtr(new((nint)_hWnd), WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, 0); - } - else - { - PInvoke.SetWindowLongPtr( - new((nint)_hWnd), - WINDOW_LONG_PTR_INDEX.GWL_EXSTYLE, - (nint)(WINDOW_EX_STYLE.WS_EX_LAYERED | WINDOW_EX_STYLE.WS_EX_COMPOSITED)); - - var dwAttrib = Convert.ToUInt32(true); - - PInvoke.DwmSetWindowAttribute( - new((nint)_hWnd), - DWMWINDOWATTRIBUTE.DWMWA_CLOAK, - &dwAttrib, - (uint)Marshal.SizeOf(dwAttrib)); - } - } - } -} - -#pragma warning restore CS8305 // Type is for evaluation purposes only and is subject to change or removal in future updates. diff --git a/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.Windows.cs deleted file mode 100644 index 4b1047c88d01..000000000000 --- a/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.Windows.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.UserControls.FilePreviews; -using Files.App.ViewModels.Properties; - -namespace Files.App.ViewModels.Previews -{ - public sealed partial class TextPreviewViewModel : BasePreviewModel - { - private string? textValue; - public string? TextValue - { - get => textValue; - private set => SetProperty(ref textValue, value); - } - - public TextPreviewViewModel(ListedItem item) - : base(item) - { - } - - public async override Task> LoadPreviewAndDetailsAsync() - { - var details = new List(); - - try - { - var text = TextValue ?? await ReadFileAsTextAsync(PreviewFile); - - details.Add(GetFileProperty("PropertyLineCount", text.Split('\n').Length)); - details.Add(GetFileProperty("PropertyWordCount", text.Split(new[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries).Length)); - - TextValue = text.Left(Constants.PreviewPane.TextCharacterLimit); - } - catch (Exception e) - { - Debug.WriteLine(e); - } - - return details; - } - - public static async Task TryLoadAsTextAsync(ListedItem item) - { - string? extension = item.FileExtension?.ToLowerInvariant(); - if (ExcludedExtensions(extension) || item.FileSizeBytes is 0 or > Constants.PreviewPane.TryLoadAsTextSizeLimit) - return null; - - try - { - item.ItemFile = await StorageFileExtensions.DangerousGetFileFromPathAsync(item.ItemPath!); - if (item.ItemFile is not { } itemFile) - return null; - - var text = await ReadFileAsTextAsync(itemFile); - bool isBinaryFile = text.Contains("\0\0\0\0", StringComparison.Ordinal); - - if (isBinaryFile) - return null; - - var model = new TextPreviewViewModel(item) { TextValue = text }; - await model.LoadAsync(); - - return new TextPreview(model); - } - catch - { - return null; - } - } - - private static bool ExcludedExtensions(string? extension) - => extension is ".iso"; - } -} - diff --git a/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.cs b/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.cs index c1b626fc69ba..6ab0f9879485 100644 --- a/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Previews/TextPreviewViewModel.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using TextPreview = Files.App.UserControls.FilePreviews.DesktopTextPreview; using ColorCode; using Files.App.UserControls.FilePreviews; @@ -161,4 +160,3 @@ private static bool ExcludedExtensions(string? extension) => extension is ".iso" or ".pdf"; } } -#endif diff --git a/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs b/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs index c91f623ae7a9..6576f996239b 100644 --- a/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs @@ -835,9 +835,7 @@ public async void HandleItemInvokedAsync(object item, PointerUpdateKind pointerU if (item is not INavigationControlItem navigationControlItem) return; var navigationPath = item as string; -#if !WINDOWS navigationPath ??= (item as DriveItem)?.Path; -#endif if (await DriveHelpers.CheckEmptyDrive(navigationPath)) return; @@ -1049,24 +1047,16 @@ private void EjectDevice() private void MountDevice() { -#if !WINDOWS _ = DriveHelpers.MountVolumeAsync(rightClickedItem.GetRequiredPath()); -#endif } private void UnmountDevice() { -#if !WINDOWS _ = DriveHelpers.UnmountVolumeAsync(rightClickedItem.GetRequiredPath()); -#endif } private static bool IsUnmountedDrive(INavigationControlItem item) -#if !WINDOWS => DriveHelpers.IsUnmountedPath(item.Path); -#else - => false; -#endif private List GetLocationItemMenuItems(INavigationControlItem item, FlyoutBase menu) { @@ -1495,11 +1485,7 @@ private async Task HandleTagItemDroppedAsync(FileTagItem fileTagItem, ItemDroppe if (!filesTags.Contains(fileTag.Uid)) { filesTags = [.. filesTags, fileTag.Uid]; -#if WINDOWS - var fileFRN = await FileTagsHelper.GetFileFRN(item.Item); -#else var fileFRN = FileTagsHelper.GetFileFRN(path); -#endif dbInstance.SetTags(path, fileFRN, filesTags); await FileTagsHelper.WriteFileTagAsync(path, filesTags); pathToTags[path] = filesTags; diff --git a/src/Files.App/ViewModels/UserControls/StatusCenterViewModel.cs b/src/Files.App/ViewModels/UserControls/StatusCenterViewModel.cs index ace58c5a1193..c8920cd88d74 100644 --- a/src/Files.App/ViewModels/UserControls/StatusCenterViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/StatusCenterViewModel.cs @@ -5,9 +5,6 @@ namespace Files.App.ViewModels.UserControls { public sealed partial class StatusCenterViewModel : ObservableObject { -#if WINDOWS - private readonly Files.App.Storage.TaskbarManager _taskbar = Files.App.Storage.TaskbarManager.Default; -#endif public ObservableCollection StatusCenterItems { get; } = []; @@ -167,26 +164,6 @@ public void UpdateAverageProgressValue() private void UpdateTaskbarProgress() { -#if WINDOWS - try - { - var hwnd = new Windows.Win32.Foundation.HWND(MainWindow.Instance.WindowHandle); - - if (HasAnyItemInProgress) - { - _taskbar.SetProgressState(hwnd, Windows.Win32.UI.Shell.TBPFLAG.TBPF_NORMAL); - _taskbar.SetProgressValue(hwnd, (ulong)Math.Clamp(AverageOperationProgressValue, 0, 100), 100); - } - else - { - _taskbar.SetProgressState(hwnd, Windows.Win32.UI.Shell.TBPFLAG.TBPF_NOPROGRESS); - } - } - catch - { - // Ignore taskbar update failures to avoid interrupting status updates. - } -#endif } } } diff --git a/src/Files.App/ViewModels/UserControls/Widgets/DrivesWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/DrivesWidgetViewModel.cs index 786b2d25d1ce..2783cdaef981 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/DrivesWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/DrivesWidgetViewModel.cs @@ -247,18 +247,14 @@ private void ExecuteEjectDeviceCommand(WidgetDriveCardItem? item) private void ExecuteMountDeviceCommand(WidgetDriveCardItem? item) { -#if !WINDOWS if (item is not null) _ = DriveHelpers.MountVolumeAsync(item.Item.Path!); -#endif } private void ExecuteUnmountDeviceCommand(WidgetDriveCardItem? item) { -#if !WINDOWS if (item is not null) _ = DriveHelpers.UnmountVolumeAsync(item.Item.Path!); -#endif } private void ExecuteOpenPropertiesCommand(WidgetDriveCardItem? item) diff --git a/src/Files.App/ViewModels/UserControls/Widgets/NetworkLocationsWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/NetworkLocationsWidgetViewModel.cs index 1ebb46f187c9..3d19a9f0e6d8 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/NetworkLocationsWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/NetworkLocationsWidgetViewModel.cs @@ -245,18 +245,14 @@ private void ExecuteEjectDeviceCommand(WidgetDriveCardItem? item) private void ExecuteMountDeviceCommand(WidgetDriveCardItem? item) { -#if !WINDOWS if (item is not null) _ = DriveHelpers.MountVolumeAsync(item.Item.Path!); -#endif } private void ExecuteUnmountDeviceCommand(WidgetDriveCardItem? item) { -#if !WINDOWS if (item is not null) _ = DriveHelpers.UnmountVolumeAsync(item.Item.Path!); -#endif } private Task ExecuteMapNetworkDriveCommand() @@ -266,11 +262,7 @@ private Task ExecuteMapNetworkDriveCommand() private void ExecuteFormatDriveCommand(WidgetDriveCardItem? item) { -#if !WINDOWS _ = DriveHelpers.OpenFormatDialogAsync(item?.Path); -#else - Win32Helper.OpenFormatDriveDialog(item?.Path ?? string.Empty); -#endif } private void ExecuteOpenPropertiesCommand(WidgetDriveCardItem? item) diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.Windows.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.Windows.cs deleted file mode 100644 index 69a744665ec2..000000000000 --- a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.Windows.cs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Windows.Win32; -using Windows.Win32.Foundation; -using Windows.Win32.System.Com; -using Windows.Win32.System.WinRT; -using Windows.Win32.UI.Shell; - -namespace Files.App.ViewModels.UserControls.Widgets -{ - public sealed partial class QuickAccessWidgetViewModel - { - private sealed record FolderSnapshot(IAgileReference ShellItem, string Text, string Path, bool IsPinned, string Tooltip); - - public Task RefreshWidgetAsync() - { - return MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => - { - if (isDisposed) - return; - - var refreshVersion = ++_refreshVersion; - var homeFolder = HomePageContext.HomeFolder; - var folders = await STATask.RunPooled(() => - { - List result = []; - // The Shell enumerator and its metadata reads stay on this persistent STA. - foreach (IWindowsStorable folder in homeFolder.GetQuickAccessFolderAsync().ToBlockingEnumerable()) - { - using (folder) - { - folder.GetPropertyValue("System.Home.IsPinned", out var isPinned); - folder.TryGetShellTooltip(out var tooltip); - var text = folder.GetDisplayName(SIGDN.SIGDN_PARENTRELATIVEFORUI); - var path = folder.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING); - var hr = PInvoke.RoGetAgileReference(AgileReferenceOptions.AGILEREFERENCE_DEFAULT, typeof(IShellItem).GUID, folder.ThisPtr, out IAgileReference shellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - continue; - - result.Add(new(shellItem, text, path, isPinned, tooltip ?? string.Empty)); - } - } - return result; - }, App.Logger); - - if (isDisposed || refreshVersion != _refreshVersion || folders is null) - return; - - foreach (var item in Items) - item.Dispose(); - - Items.Clear(); - - foreach (var folder in folders) - { - if (folder.ShellItem.Resolve(out IShellItem shellItem).ThrowIfFailedOnDebug().Failed) - continue; - - Items.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem), folder.Text, folder.Path, folder.IsPinned, folder.Tooltip)); - } - }); - } - - - public override async Task ExecutePinToSidebarCommand(WidgetCardItem? item) - { - if (item is not WidgetFolderCardItem folderCardItem || folderCardItem.Path is null) - return; - - - - var lastPinnedItemIndex = Items.LastOrDefault(x => x.IsPinned) is { } lastPinnedItem ? Items.IndexOf(lastPinnedItem) : 0; - var currentPinnedItemIndex = Items.IndexOf(folderCardItem); - - if (currentPinnedItemIndex is -1) - return; - - HRESULT hr = PInvoke.RoGetAgileReference(AgileReferenceOptions.AGILEREFERENCE_DEFAULT, typeof(IShellItem).GUID, ((IWindowsStorable)folderCardItem.Item).ThisPtr, out IAgileReference pAgileReference); - if (hr.ThrowIfFailedOnDebug().Failed) - return; - - // Pin to Quick Access on Windows - hr = await STATask.Run(() => - { - hr = pAgileReference.Resolve(out IShellItem pShellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - using var windowsFile = new WindowsFile(pShellItem); - // NOTE: "pintohome" is an undocumented verb, which calls an undocumented COM class, windows.storage.dll!CPinToFrequentExecute : public IExecuteCommand, ... - return windowsFile.TryInvokeContextMenuVerb("pintohome"); - }, App.Logger); - - // The file watcher will update the collection automatically - } - - - public override async Task ExecuteUnpinFromSidebarCommand(WidgetCardItem? item) - { - if (item is not WidgetFolderCardItem folderCardItem || folderCardItem.Path is null) - return; - - - - HRESULT hr = PInvoke.RoGetAgileReference(AgileReferenceOptions.AGILEREFERENCE_DEFAULT, typeof(IShellItem).GUID, ((IWindowsStorable)folderCardItem.Item).ThisPtr, out IAgileReference pAgileReference); - if (hr.ThrowIfFailedOnDebug().Failed) - return; - - // Unpin from Quick Access on Windows - hr = await STATask.Run(() => - { - hr = pAgileReference.Resolve(out IShellItem pShellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - return hr; - - using var windowsFile = new WindowsFile(pShellItem); - - // NOTE: "unpinfromhome" is an undocumented verb, which calls an undocumented COM class, windows.storage.dll!CRemoveFromFrequentPlacesExecute : public IExecuteCommand, ... - // NOTE: "remove" is for some shell folders where the "unpinfromhome" may not work - return windowsFile.TryInvokeContextMenuVerbs(["unpinfromhome", "remove"], true); - }, App.Logger); - - if (hr.ThrowIfFailedOnDebug().Failed) - return; - - // The file watcher will update the collection automatically - } - - } -} diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs index bc8575e4a9fe..c5f16ef96e52 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs @@ -45,26 +45,8 @@ public QuickAccessWidgetViewModel() PinToSidebarCommand = new AsyncRelayCommand(ExecutePinToSidebarCommand); UnpinFromSidebarCommand = new AsyncRelayCommand(ExecuteUnpinFromSidebarCommand); -#if !WINDOWS App.QuickAccessManager.UpdateQuickAccessWidget += QuickAccessChanged; -#endif -#if WINDOWS - var automaticDestinationsPath = SystemIO.Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "Recent", "AutomaticDestinations"); - if (!SystemIO.Directory.Exists(automaticDestinationsPath)) - return; - - _quickAccessFolderWatcher = new() - { - Path = automaticDestinationsPath, - Filter = "f01b4d95cf55d32a.automaticDestinations-ms", - NotifyFilter = SystemIO.NotifyFilters.LastAccess | SystemIO.NotifyFilters.LastWrite | SystemIO.NotifyFilters.FileName - }; - - _quickAccessFolderWatcher.Changed += QuickAccessFolderWatcher_Changed; - - _quickAccessFolderWatcher.EnableRaisingEvents = true; -#endif } // Methods @@ -75,7 +57,6 @@ private async void QuickAccessFolderWatcher_Changed(object sender, SystemIO.File await RefreshWidgetAsync(); } -#if !WINDOWS private async void QuickAccessChanged(object? sender, ModifyQuickAccessEventArgs e) { if (!isDisposed) @@ -107,7 +88,6 @@ public Task RefreshWidgetAsync() }); } -#endif public override List GetItemMenuItems(WidgetCardItem item, bool isPinned, bool isFolder = false) { @@ -236,7 +216,6 @@ private async void Items_CollectionChanged(object? sender, NotifyCollectionChang // Command methods -#if !WINDOWS public override async Task ExecutePinToSidebarCommand(WidgetCardItem? item) { if (item is not WidgetFolderCardItem folderCardItem || folderCardItem.Path is null) @@ -244,9 +223,7 @@ public override async Task ExecutePinToSidebarCommand(WidgetCardItem? item) await QuickAccessService.PinToSidebarAsync(folderCardItem.Path); } -#endif -#if !WINDOWS public override async Task ExecuteUnpinFromSidebarCommand(WidgetCardItem? item) { if (item is not WidgetFolderCardItem folderCardItem || folderCardItem.Path is null) @@ -254,7 +231,6 @@ public override async Task ExecuteUnpinFromSidebarCommand(WidgetCardItem? item) await QuickAccessService.UnpinFromSidebarAsync(folderCardItem.Path); } -#endif private void ExecuteOpenPropertiesCommand(WidgetFolderCardItem? item) { @@ -281,17 +257,6 @@ async void FlyoutClosed(object? sender, object args) ItemType = Strings.Folder.GetLocalizedResource(), }; -#if WINDOWS - if (!string.Equals(itemPath, Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - { - BaseStorageFolder? matchingStorageFolder = (await shellViewModel.GetFolderFromPathAsync(itemPath)).Result; - if (matchingStorageFolder is not null) - { - var syncStatus = await shellViewModel.CheckCloudDriveSyncStatusAsync(matchingStorageFolder); - listedItem.SyncStatusUI = CloudDriveSyncStatusUI.FromCloudDriveSyncStatus(syncStatus); - } - } -#endif FilePropertiesHelpers.OpenPropertiesWindow(listedItem, shellPage); } @@ -308,9 +273,7 @@ public void Dispose() isDisposed = true; Items.CollectionChanged -= Items_CollectionChanged; -#if !WINDOWS App.QuickAccessManager.UpdateQuickAccessWidget -= QuickAccessChanged; -#endif if (_quickAccessFolderWatcher is not null) { _quickAccessFolderWatcher.EnableRaisingEvents = false; diff --git a/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs index 931d90408085..615682977153 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs @@ -235,34 +235,15 @@ public void NavigateToPath(string path) { var directoryName = Path.GetDirectoryName(path); -#if !WINDOWS _ = NavigationHelpers.OpenPath(path, ContentPageContext.ShellPage!, FilesystemItemType.File); -#else - _ = Win32Helper.InvokeWin32ComponentAsync(path, ContentPageContext.ShellPage!, workingDirectory: directoryName ?? string.Empty); -#endif } catch (Exception) { } } public bool CheckIsRecentItemsEnabled() { -#if !WINDOWS // LINUX-TODO(recent): honour org.gnome.desktop.privacy remember-recent-files return true; -#else - using var explorerSubKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"); - using var advSubkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced"); - using var userPolicySubkey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"); - using var sysPolicySubkey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"); - var policySubkey = userPolicySubkey ?? sysPolicySubkey; - - if (Convert.ToBoolean(explorerSubKey?.GetValue("ShowRecent", true)) && - Convert.ToBoolean(advSubkey?.GetValue("Start_TrackDocs", true)) && - !Convert.ToBoolean(policySubkey?.GetValue("NoRecentDocsHistory", false))) - return true; - - return false; -#endif } // Event methods @@ -364,12 +345,6 @@ async void FlyoutClosed(object? sender, object args) } else { -#if WINDOWS - var listedItem = await UniversalStorageEnumerator.AddFileAsync(file, null, default); - var shellPage = ContentPageContext.ShellPage - ?? throw new InvalidOperationException("The shell page is not available for opening properties."); - FilePropertiesHelpers.OpenPropertiesWindow(listedItem!, shellPage); -#endif } } diff --git a/src/Files.App/Views/Layouts/BaseGroupableLayoutPage.cs b/src/Files.App/Views/Layouts/BaseGroupableLayoutPage.cs index cd44d0e86d0f..03dd20c519df 100644 --- a/src/Files.App/Views/Layouts/BaseGroupableLayoutPage.cs +++ b/src/Files.App/Views/Layouts/BaseGroupableLayoutPage.cs @@ -12,9 +12,6 @@ using System.Runtime.InteropServices; using Windows.System; using Windows.UI.Core; -#if WINDOWS -using Windows.Win32; -#endif using WinRT; namespace Files.App.Views.Layouts @@ -26,21 +23,16 @@ public abstract class BaseGroupableLayoutPage : BaseLayoutPage { // Constants -#if WINDOWS - private const int KEY_DOWN_MASK = 0x8000; -#endif // Fields protected int NextRenameIndex = 0; -#if !WINDOWS private bool isSelectingAll; private Microsoft.UI.Dispatching.DispatcherQueueTimer? listJumpTimer; private ListedItem? pendingListJumpItem; private ListedItem? lastListJumpItem; private int pendingListJumpIndex; private int listJumpPageSize = 1; -#endif protected TextBox? renameTextBox; // Properties @@ -54,9 +46,7 @@ public abstract class BaseGroupableLayoutPage : BaseLayoutPage public BaseGroupableLayoutPage() : base() { -#if !WINDOWS Unloaded += (_, _) => CancelListJump(); -#endif } // Abstract methods @@ -113,17 +103,13 @@ protected override void HookEvents() ItemManipulationModel.ScrollToTopInvoked += ItemManipulationModel_ScrollToTopInvoked; ItemManipulationModel.RefreshItemThumbnailInvoked += ItemManipulationModel_RefreshItemThumbnail; ItemManipulationModel.RefreshItemsThumbnailInvoked += ItemManipulationModel_RefreshItemsThumbnail; -#if !WINDOWS ActualThemeChanged -= LinuxPage_ActualThemeChanged; ActualThemeChanged += LinuxPage_ActualThemeChanged; -#endif } protected override void UnhookEvents() { -#if !WINDOWS CancelListJump(); -#endif if (ItemManipulationModel is null) return; @@ -246,9 +232,6 @@ protected virtual void ItemManipulationModel_FocusFileListInvoked(object? sender protected virtual void ItemManipulationModel_SelectAllItemsInvoked(object? sender, EventArgs e) { -#if WINDOWS - ListViewBase.SelectAll(); -#else using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("select-all", DispatcherQueue.HasThreadAccess); // Uno doesn't implement SelectAll. Each Add raises SelectionChanged, so update the page once at the end instead of per item. var selected = ListViewBase.SelectedItems.ToHashSet(ReferenceEqualityComparer.Instance); @@ -268,7 +251,6 @@ protected virtual void ItemManipulationModel_SelectAllItemsInvoked(object? sende } FileList_SelectionChanged(ListViewBase, new SelectionChangedEventArgs([], added)); -#endif } protected virtual void ItemManipulationModel_ClearSelectionInvoked(object? sender, EventArgs e) @@ -313,15 +295,12 @@ protected virtual void FileList_SelectionChanged(object sender, SelectionChanged if (e is not null && e.AddedItems.Count == 0 && e.RemovedItems.Count == 0) return; -#if !WINDOWS if (isSelectingAll) return; foreach (var header in ListViewBase.SelectedItems.Where(x => x is not ListedItem).ToList()) ListViewBase.SelectedItems.Remove(header); -#endif var selectedItems = ListViewBase.SelectedItems.OfType().ToList(); -#if !WINDOWS if (e is not null) { if (e.AddedItems.Count > 1 && ListViewBase.ItemsPanelRoot is { } panel) @@ -336,7 +315,6 @@ protected virtual void FileList_SelectionChanged(object sender, SelectionChanged ApplyPageThemeToContainer(ListViewBase.ContainerFromItem(added) as FrameworkElement); } } -#endif if (SelectedItems is not null && SelectedItems.SequenceEqual(selectedItems)) return; @@ -367,7 +345,6 @@ protected virtual void SelectionRectangle_SelectionEnded(object? sender, EventAr /// Uno can leave a container (and the rename box inside it) with the application theme instead of the page's /// theme after the rename box takes focus, which paints dark-theme text on a light row and vice versa. /// -#if !WINDOWS /// /// A selected container resolves its text brushes against the application theme instead of the page theme on Uno, /// which paints white text on a light selection, so the page theme is pinned on the container. @@ -386,7 +363,6 @@ private void LinuxPage_ActualThemeChanged(FrameworkElement sender, object args) foreach (var child in panel.Children) ApplyPageThemeToContainer(child as FrameworkElement); } -#endif protected void SyncContainerTheme(FrameworkElement? container) { @@ -796,13 +772,7 @@ private void CancelListJump() protected async void RenameTextBox_KeyDown(object sender, KeyRoutedEventArgs e) { var textBox = (TextBox)sender; -#if WINDOWS - var isShiftPressed = OperatingSystem.IsWindows() - ? (PInvoke.GetKeyState((int)VirtualKey.Shift) & KEY_DOWN_MASK) != 0 - : Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); -#else var isShiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); -#endif switch (e.Key) { diff --git a/src/Files.App/Views/Layouts/BaseLayoutPage.Linux.cs b/src/Files.App/Views/Layouts/BaseLayoutPage.Linux.cs index bb808d118743..e55d17dc22b1 100644 --- a/src/Files.App/Views/Layouts/BaseLayoutPage.Linux.cs +++ b/src/Files.App/Views/Layouts/BaseLayoutPage.Linux.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Microsoft.UI.Xaml.Controls; namespace Files.App.Views.Layouts @@ -33,4 +32,3 @@ private void DisposeLinuxGroupedItemsSource() } } } -#endif diff --git a/src/Files.App/Views/Layouts/BaseLayoutPage.cs b/src/Files.App/Views/Layouts/BaseLayoutPage.cs index 04016f7d736f..98c568da515b 100644 --- a/src/Files.App/Views/Layouts/BaseLayoutPage.cs +++ b/src/Files.App/Views/Layouts/BaseLayoutPage.cs @@ -22,9 +22,6 @@ using Windows.Foundation.Collections; using Windows.Storage; using Windows.System; -#if WINDOWS -using Windows.Win32; -#endif using WinRT; using static Files.App.Helpers.PathNormalization; using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; @@ -75,7 +72,6 @@ public abstract partial class BaseLayoutPage : Page, IBaseLayoutPage, INotifyPro private CancellationTokenSource? shellContextMenuItemCancellationToken; private CancellationTokenSource? groupingCancellationToken; -#if !WINDOWS private long contextMenuVersion; private void InvalidateContextMenuBuild() @@ -89,7 +85,6 @@ private void ContextMenuContextChanged(object? sender, PropertyChangedEventArgs if (e.PropertyName is nameof(ShellViewModel.WorkingDirectory) or nameof(ShellViewModel.CurrentFolder)) InvalidateContextMenuBuild(); } -#endif private bool shiftPressed; private bool itemDragging; @@ -194,11 +189,7 @@ public bool IsMiddleClickToScrollEnabled /// // LINUX-TODO(listing): fall back to CollectionViewSource.View once Uno's CollectionView handles bulk Reset public object? LayoutItemsSource -#if WINDOWS - => CollectionViewSource.View; -#else => linuxGroupedItemsSource?.Items ?? CollectionViewSource.Source; -#endif public CollectionViewSource CollectionViewSource { @@ -212,9 +203,7 @@ public CollectionViewSource CollectionViewSource collectionViewSource.View.VectorChanged -= View_VectorChanged; collectionViewSource = value; -#if !WINDOWS UpdateLinuxGroupedItemsSource(); -#endif NotifyPropertyChanged(nameof(CollectionViewSource)); NotifyPropertyChanged(nameof(LayoutItemsSource)); @@ -333,9 +322,7 @@ internal set if (value != selectedItems) { isSelectedItemsSorted = false; -#if !WINDOWS InvalidateContextMenuBuild(); -#endif selectedItems = value; var currentItems = value; @@ -434,11 +421,9 @@ private void HookBaseEvents() private void UnhookBaseEvents() { -#if !WINDOWS InvalidateContextMenuBuild(); if (ParentShellPageInstance?.ShellViewModel is { } shellViewModel) shellViewModel.PropertyChanged -= ContextMenuContextChanged; -#endif ItemManipulationModel.RefreshItemsOpacityInvoked -= ItemManipulationModel_RefreshItemsOpacityInvoked; jumpTimer?.Stop(); if (jumpTimer is not null) @@ -710,9 +695,7 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) SetSelectedItemsOnNavigation(); -#if !WINDOWS shellViewModel.PropertyChanged += ContextMenuContextChanged; -#endif ItemContextMenuFlyout.Opening += ItemContextFlyout_Opening; BaseContextMenuFlyout.Opening += BaseContextFlyout_Opening; @@ -754,9 +737,7 @@ private CancellationToken RenewShellMenuToken() [DynamicWindowsRuntimeCast(typeof(MenuFlyout))] private async void ItemContextFlyout_Opening(object? sender, object e) { -#if !WINDOWS using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-build", DispatcherQueue.HasThreadAccess); -#endif var token = RenewShellMenuToken(); try { @@ -781,9 +762,6 @@ private async void ItemContextFlyout_Opening(object? sender, object e) shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); SelectedItemsPropertiesViewModel.CheckAllFileExtensions(selectedItems.Select(x => x.FileExtension).ToList()); -#if WINDOWS - var items = ContentPageContextFlyoutFactory.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: instanceViewModel, selectedItems: selectedItems, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: commandsViewModel, shiftPressed: shiftPressed, itemViewModel: null); -#else token = RenewShellMenuToken(); var buildVersion = contextMenuVersion; ItemContextFlyoutHost.Reset(); @@ -792,16 +770,9 @@ private async void ItemContextFlyout_Opening(object? sender, object e) token.ThrowIfCancellationRequested(); if (buildVersion != contextMenuVersion || !parentShellPage.IsCurrentInstance || !parentShellPage.IsCurrentPane) return; -#endif var host = ItemContextFlyoutHost; -#if !WINDOWS using (Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-flyout", true)) -#endif -#if WINDOWS - host.Build(items); -#else host.Build(items, preservePlacement: true); -#endif // Edit tags: a submenu of the available tags (FileTagsContextMenu is a standalone MenuFlyout that // can't be nested, so build the tag toggles directly). @@ -858,9 +829,7 @@ private async void ItemContextFlyout_Opening(object? sender, object e) } host.FinalizePrimaryRowPosition(); -#if !WINDOWS host.CorrectRebuiltPlacement(); -#endif } catch (OperationCanceledException) when (token.IsCancellationRequested) { @@ -1021,19 +990,15 @@ private async Task GroupPreferenceUpdatedAsync() protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { base.OnNavigatingFrom(e); -#if !WINDOWS InvalidateContextMenuBuild(); ParentShellPageInstance.GetRequiredShellViewModel().PropertyChanged -= ContextMenuContextChanged; -#endif shellContextMenuItemCancellationToken?.Cancel(); navigationArguments = null; // Remove item jumping handler CharacterReceived -= Page_CharacterReceived; UnhookScrollDeferTracking(); -#if !WINDOWS DisposeLinuxGroupedItemsSource(); -#endif var folderSettings = FolderSettings ?? throw new InvalidOperationException("The layout does not have folder settings."); folderSettings.LayoutModeChangeRequested -= BaseFolderSettings_LayoutModeChangeRequested; @@ -1060,9 +1025,7 @@ protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) private async void BaseContextFlyout_Opening(object? sender, object e) { -#if !WINDOWS using var trace = Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-build", DispatcherQueue.HasThreadAccess); -#endif var token = RenewShellMenuToken(); try { @@ -1078,9 +1041,6 @@ private async void BaseContextFlyout_Opening(object? sender, object e) var currentFolder = shellViewModel.CurrentFolder ?? throw new InvalidOperationException("The current folder is not available."); List contextItems = [currentFolder]; -#if WINDOWS - var items = ContentPageContextFlyoutFactory.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: instanceViewModel, selectedItems: contextItems, commandsViewModel: commandsViewModel, shiftPressed: shiftPressed, itemViewModel: shellViewModel, selectedItemsPropertiesViewModel: null); -#else token = RenewShellMenuToken(); var buildVersion = contextMenuVersion; BaseContextFlyoutHost.Reset(); @@ -1089,16 +1049,9 @@ private async void BaseContextFlyout_Opening(object? sender, object e) token.ThrowIfCancellationRequested(); if (buildVersion != contextMenuVersion || !parentShellPage.IsCurrentInstance || !parentShellPage.IsCurrentPane) return; -#endif var host = BaseContextFlyoutHost; -#if !WINDOWS using (Files.Platform.Abstractions.Diagnostics.PerformanceTrace.Begin("context-menu-flyout", true)) -#endif -#if WINDOWS - host.Build(items); -#else host.Build(items, preservePlacement: true); -#endif if (!instanceViewModel.IsPageTypeSearchResults && !instanceViewModel.IsPageTypeZipFolder && !instanceViewModel.IsPageTypeFtp) { @@ -1127,9 +1080,7 @@ private async void BaseContextFlyout_Opening(object? sender, object e) } host.FinalizePrimaryRowPosition(); -#if !WINDOWS host.CorrectRebuiltPlacement(); -#endif } catch (OperationCanceledException) when (token.IsCancellationRequested) { @@ -1189,44 +1140,11 @@ protected virtual void FileList_DragItemsStarting(object sender, DragItemsStarti var sortedItems = SortingHelper.OrderFileList(itemList, folderSettings.DirectorySortOption, folderSettings.DirectorySortDirection, folderSettings.SortDirectoriesAlongsideFiles, folderSettings.SortFilesFirst).ToList(); var orderedItems = sortedItems.SkipWhile(x => x != firstItem).Concat(sortedItems.TakeWhile(x => x != firstItem)).ToList(); -#if WINDOWS - var shellItemList = SafetyExtensions.IgnoreExceptions(() => orderedItems.Select(item => new ShellItem(item.GetRequiredPath())).ToArray()); - try - { - if (shellItemList?[0].FileSystemPath is not null && !instanceViewModel.IsPageTypeSearchResults) - { - var dataObject = ShellDataObject.Create(shellItemList); - if (ShellDataObject.GetShellIdListArray(dataObject) is byte[] data) - { - var stream = new MemoryStream(data).AsRandomAccessStream(); - e.Data.SetData(ShellDataObject.ShellIdListArrayFormat, stream); - } - } - else - { - // Only support IStorageItem capable paths -#if WINDOWS - var storageItemList = orderedItems.Where(x => !(x.IsHiddenItem && x.IsLinkItem && x.IsRecycleBinItem && x.IsShortcut)).Select(x => VirtualStorageItem.FromListedItem(x)).ToArray(); - e.Data.SetStorageItems(storageItemList, false); -#endif - } - } - finally - { - if (shellItemList is not null) - { - foreach (ShellItem item in shellItemList) - item.Dispose(); - } - } -#endif // Set can window to front (#13255) MainWindow.Instance.SetCanWindowToFront(false); itemDragging = true; -#if !WINDOWS Files.App.Services.Desktop.DesktopFileDragHelper.StartExternalDrag(orderedItems.Select(x => x.ItemPath)); -#endif } catch (Exception) { @@ -1403,10 +1321,8 @@ await SafetyExtensions.IgnoreExceptions(async () => protected void FileList_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) { HookScrollDeferTracking(); -#if !WINDOWS if (args.Item is ContentControl { Content: IGroupedCollectionHeader }) return; -#endif RefreshContainer(args.ItemContainer, args.InRecycleQueue); RefreshItem(args.ItemContainer, args.Item, args.InRecycleQueue, args); @@ -1557,19 +1473,6 @@ private void RefreshItem(SelectorItem container, object item, bool inRecycleQueu if (!listedItem.ItemPropertiesInitialized) { -#if WINDOWS - uint callbackPhase = 3; - args.RegisterUpdateCallback(callbackPhase, async (s, c) => - { - var shellViewModel = ParentShellPageInstance.GetRequiredShellViewModel(); - - // Rows realized mid-scroll are mostly flung past before the gesture ends; the settle pass loads the ones still visible - if (shellViewModel.IsScrollInFlight) - return; - - await LoadItemExtendedPropertiesAsync(listedItem, shellViewModel); - }); -#else // Uno never raises the phased update callback, so rows were never loaded until the first scroll (no tags, no properties) DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, async () => { @@ -1580,7 +1483,6 @@ private void RefreshItem(SelectorItem container, object item, bool inRecycleQueu await LoadItemExtendedPropertiesAsync(listedItem, shellViewModel); }); -#endif } } } @@ -1630,10 +1532,6 @@ private void FileListItem_Loaded(object sender, RoutedEventArgs e) protected internal void FileListItem_PointerPressed(object sender, PointerRoutedEventArgs e) { // Set can window to front and bring the window to the front if necessary (#13255) -#if WINDOWS - if ((!itemDragging) && MainWindow.Instance.SetCanWindowToFront(true)) - Win32Helper.BringToForegroundEx(new(MainWindow.Instance.WindowHandle)); -#endif if (sender is not SelectorItem selectorItem) return; @@ -1728,29 +1626,17 @@ protected internal void FileListItem_PointerExited(object sender, PointerRoutedE protected void FileListItem_Tapped(object sender, TappedRoutedEventArgs e) { // Set can window to front and bring the window to the front if necessary (#13255) -#if WINDOWS - if ((!itemDragging) && MainWindow.Instance.SetCanWindowToFront(true)) - Win32Helper.BringToForegroundEx(new(MainWindow.Instance.WindowHandle)); -#endif } protected void FileListItem_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { // Set can window to front and bring the window to the front if necessary (#13255) -#if WINDOWS - if ((!itemDragging) && MainWindow.Instance.SetCanWindowToFront(true)) - Win32Helper.BringToForegroundEx(new(MainWindow.Instance.WindowHandle)); -#endif } [DynamicWindowsRuntimeCast(typeof(SelectorItem))] protected void FileListItem_RightTapped(object sender, RightTappedRoutedEventArgs e) { // Set can window to front and bring the window to the front if necessary (#13255) -#if WINDOWS - if ((!itemDragging) && MainWindow.Instance.SetCanWindowToFront(true)) - Win32Helper.BringToForegroundEx(new(MainWindow.Instance.WindowHandle)); -#endif var rightClickedItem = GetItemFromElement(sender); @@ -1792,9 +1678,7 @@ public virtual void Dispose() UnhookBaseEvents(); UnhookScrollDeferTracking(); StatusBarViewModel.Dispose(); -#if !WINDOWS DisposeLinuxGroupedItemsSource(); -#endif dragOverItem = null; hoveredItem = null; preRenamingItem = null; @@ -1820,9 +1704,7 @@ private void UpdateCollectionViewSource() { // Replacing the source rebuilds the list from scratch (a visible empty flash), so keep it when unchanged if (CollectionViewSource.IsSourceGrouped && ReferenceEquals(CollectionViewSource.Source, shellViewModel.FilesAndFolders.GroupedCollection) -#if !WINDOWS && linuxGroupedItemsSource is not null -#endif ) return; @@ -1931,11 +1813,7 @@ public void CheckRenameDoubleClick(object? clickedItem) tapDebounceTimer?.Stop(); } }, -#if WINDOWS - TimeSpan.FromMilliseconds(OperatingSystem.IsWindows() ? PInvoke.GetDoubleClickTime() : 500)); -#else TimeSpan.FromMilliseconds(500)); -#endif } else { diff --git a/src/Files.App/Views/Layouts/ColumnLayoutPage.xaml.cs b/src/Files.App/Views/Layouts/ColumnLayoutPage.xaml.cs index 4a25f89e9f02..c4374300ec0f 100644 --- a/src/Files.App/Views/Layouts/ColumnLayoutPage.xaml.cs +++ b/src/Files.App/Views/Layouts/ColumnLayoutPage.xaml.cs @@ -83,9 +83,7 @@ public int IconBoxSize public ColumnLayoutPage() : base() { InitializeComponent(); -#if !WINDOWS HoistSemanticZoomContent(RootGridZoom); -#endif var selectionRectangle = RectangleSelection.Create(FileList, SelectionRectangle, FileList_SelectionChanged); selectionRectangle.SelectionStarted += SelectionRectangle_SelectionStarted; selectionRectangle.SelectionEnded += SelectionRectangle_SelectionEnded; diff --git a/src/Files.App/Views/Layouts/DetailsLayoutPage.xaml.cs b/src/Files.App/Views/Layouts/DetailsLayoutPage.xaml.cs index 5740c2662df5..9c885f4455fb 100644 --- a/src/Files.App/Views/Layouts/DetailsLayoutPage.xaml.cs +++ b/src/Files.App/Views/Layouts/DetailsLayoutPage.xaml.cs @@ -46,9 +46,7 @@ public sealed partial class DetailsLayoutPage : BaseGroupableLayoutPage private DetailsViewSizeKind? itemContainerSize; private DispatcherQueueTimer? _autoFitColumnsTimer; -#if !WINDOWS private ScrollViewer? linuxHeaderScroller; -#endif // Properties @@ -93,14 +91,12 @@ public int RowHeight public DetailsLayoutPage() : base() { InitializeComponent(); -#if !WINDOWS HeaderGrid.Margin = new Thickness(0); HeaderGrid.Padding = new Thickness(16, 0, 0, 0); ActualThemeChanged += (_, _) => UpdateLinuxListTheme(); HoistSemanticZoomContent(RootGridZoom); InitializeLinuxHeader(); Unloaded += (_, _) => DetachLinuxHeaderScroller(); -#endif DataContext = this; var selectionRectangle = RectangleSelection.Create(FileList, SelectionRectangle, FileList_SelectionChanged); selectionRectangle.SelectionStarted += SelectionRectangle_SelectionStarted; @@ -249,9 +245,7 @@ protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) public override void Dispose() { -#if !WINDOWS DetachLinuxHeaderScroller(); -#endif Bindings.StopTracking(); if (FolderSettings is { } folderSettings) { @@ -808,7 +802,6 @@ private void StackPanel_Loaded(object sender, RoutedEventArgs e) itemContainer.ContextFlyout = ItemContextMenuFlyout; } -#if !WINDOWS private void InitializeLinuxHeader() { // Uno cannot animate a scrolling header with GetScrollViewerManipulationPropertySet. @@ -860,7 +853,6 @@ private void UpdateLinuxListTheme() FileList.RequestedTheme = ActualTheme; HeaderGrid.RequestedTheme = ActualTheme; } -#endif private void Grid_PointerPressed(object sender, PointerRoutedEventArgs e) { @@ -1151,18 +1143,14 @@ private bool IsCorrectColumn(FrameworkElement element, int columnIndex) private void FileList_Loaded(object sender, RoutedEventArgs e) { -#if !WINDOWS UpdateLinuxListTheme(); DetachLinuxHeaderScroller(); -#endif ContentScroller = FileList.FindDescendant(x => x.Name == "ScrollViewer"); -#if !WINDOWS if (ContentScroller is { } linuxScroller) { linuxScroller.ViewChanged += LinuxContentScroller_ViewChanged; SynchronizeLinuxHeader(); } -#endif const double OffsetCorrection = 88; // HeaderGrid (40) + ListViewHeaderItem (44 + 4 margin) if (RootGridZoom is not null) diff --git a/src/Files.App/Views/Layouts/GridLayoutPage.xaml.cs b/src/Files.App/Views/Layouts/GridLayoutPage.xaml.cs index 94ffefbab643..561cb5f6dcb0 100644 --- a/src/Files.App/Views/Layouts/GridLayoutPage.xaml.cs +++ b/src/Files.App/Views/Layouts/GridLayoutPage.xaml.cs @@ -47,11 +47,9 @@ public sealed partial class GridLayoutPage : BaseGroupableLayoutPage /// size changes, even if the layout size changes (since some layout sizes share the same icon size). ///
private uint currentIconSize; -#if !WINDOWS private XamlRoot? iconXamlRoot; private double iconRasterizationScale = 1; private int iconReloadRequest; -#endif private (FolderLayoutModes? Layout, ListViewSizeKind List, CardsViewSizeKind Cards, GridViewSizeKind Grid)? itemContainerLayout; private volatile bool shouldSetVerticalScrollMode; @@ -182,12 +180,8 @@ protected override (int First, int Last) GetVisibleIndexRange() public GridLayoutPage() : base() { InitializeComponent(); -#if WINDOWS - CommunityToolkit.WinUI.Animations.ItemsReorderAnimation.SetDuration(FileList, TimeSpan.FromMilliseconds(350)); -#else HoistSemanticZoomContent(RootGridZoom); // LINUX-TODO(listing): ItemsReorderAnimation is Windows-only; Uno lacks CreateImplicitAnimationCollection -#endif DataContext = this; var selectionRectangle = RectangleSelection.Create(ListViewBase, SelectionRectangle, FileList_SelectionChanged); @@ -199,7 +193,6 @@ public GridLayoutPage() : base() protected override void ItemManipulationModel_ScrollIntoViewInvoked(object? sender, ListedItem e) { -#if !WINDOWS if (FileList.ItemsPanelRoot is Files.App.UnoVirtualization.GroupedVirtualizingWrapGrid grouped) { grouped.EnsureItemVisible(e, () => @@ -209,9 +202,7 @@ protected override void ItemManipulationModel_ScrollIntoViewInvoked(object? send }); return; } -#endif FileList.ScrollIntoView(e); -#if !WINDOWS // The virtualizing panel only knows a virtual strip per item; make sure the whole cell is in view if (FileList.ItemsPanelRoot is Files.App.UnoVirtualization.VirtualizingWrapGrid panel) { @@ -225,7 +216,6 @@ protected override void ItemManipulationModel_ScrollIntoViewInvoked(object? send panel.EnsureItemVisible(index); }); } -#endif } protected override void ItemManipulationModel_ScrollToTopInvoked(object? sender, EventArgs e) @@ -241,7 +231,6 @@ protected override void ItemManipulationModel_FocusSelectedItemsInvoked(object? { if (SelectedItems.Any()) { -#if !WINDOWS if (FileList.ItemsPanelRoot is Files.App.UnoVirtualization.GroupedVirtualizingWrapGrid grouped) { var item = SelectedItems.Last(); @@ -252,7 +241,6 @@ protected override void ItemManipulationModel_FocusSelectedItemsInvoked(object? }); } else -#endif FileList.ScrollIntoView(SelectedItems.Last()); (FileList.ContainerFromItem(SelectedItems.Last()) as GridViewItem)?.Focus(FocusState.Keyboard); } @@ -309,11 +297,9 @@ protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) FolderSettings.LayoutModeChangeRequested -= FolderSettings_LayoutModeChangeRequested; UserSettingsService.LayoutSettingsService.PropertyChanged -= LayoutSettingsService_PropertyChanged; -#if !WINDOWS if (iconXamlRoot is not null) iconXamlRoot.Changed -= IconXamlRoot_Changed; iconReloadRequest++; -#endif } public override void Dispose() @@ -323,11 +309,9 @@ public override void Dispose() FolderSettings.LayoutModeChangeRequested -= FolderSettings_LayoutModeChangeRequested; UserSettingsService.LayoutSettingsService.PropertyChanged -= LayoutSettingsService_PropertyChanged; -#if !WINDOWS if (iconXamlRoot is not null) iconXamlRoot.Changed -= IconXamlRoot_Changed; iconReloadRequest++; -#endif base.Dispose(); } @@ -395,7 +379,6 @@ private void FolderSettings_LayoutModeChangeRequested(object? sender, LayoutMode } } -#if !WINDOWS private (bool Grouped, bool Virtualized, FolderLayoutModes? Mode, ListViewSizeKind List, CardsViewSizeKind Cards, GridViewSizeKind Grid)? _appliedPanelKey; private int _ensureVisibleRequest; private static bool s_loggedPanelFallback; @@ -464,7 +447,6 @@ private void UpdateItemsPanel() ProvisionalCellSize = cellSize, }); } -#endif [DynamicWindowsRuntimeCast(typeof(Style))] private void SetItemTemplate() @@ -472,13 +454,8 @@ private void SetItemTemplate() var folderSettings = FolderSettings ?? throw new InvalidOperationException("The grid layout does not have folder settings."); -#if WINDOWS - const string verticalStyleKey = "VerticalLayoutGridView"; - const string horizontalStyleKey = "HorizontalLayoutGridView"; -#else const string verticalStyleKey = "WrapVerticalLayoutGridView"; const string horizontalStyleKey = "WrapHorizontalLayoutGridView"; -#endif var newFileListStyle = folderSettings.LayoutMode switch { FolderLayoutModes.ListView => (Style)Resources[verticalStyleKey], @@ -491,11 +468,9 @@ private void SetItemTemplate() var oldSource = FileList.ItemsSource; FileList.ItemsSource = null; FileList.Style = newFileListStyle; -#if !WINDOWS _appliedPanelKey = null; FileList.ClearValue(ItemsControl.ItemsPanelProperty); UpdateItemsPanel(); -#endif FileList.ItemsSource = oldSource; } @@ -549,15 +524,12 @@ private void SetItemContainerStyle() } } itemContainerLayout = layout; -#if !WINDOWS UpdateItemsPanel(); -#endif } private void FileList_Loaded(object sender, RoutedEventArgs e) { ContentScroller = FileList.FindDescendant(x => x.Name == "ScrollViewer"); -#if !WINDOWS if (iconXamlRoot is not null) iconXamlRoot.Changed -= IconXamlRoot_Changed; iconXamlRoot = XamlRoot; @@ -566,10 +538,8 @@ private void FileList_Loaded(object sender, RoutedEventArgs e) iconXamlRoot.Changed += IconXamlRoot_Changed; IconXamlRoot_Changed(iconXamlRoot, null!); } -#endif } -#if !WINDOWS private void IconXamlRoot_Changed(XamlRoot sender, XamlRootChangedEventArgs args) { if (Math.Abs(iconRasterizationScale - sender.RasterizationScale) < 0.01) @@ -580,7 +550,6 @@ private void IconXamlRoot_Changed(XamlRoot sender, XamlRootChangedEventArgs args Ioc.Default.GetRequiredService().Clear(); _ = ReloadItemIconsAsync(); } -#endif protected override void OnSelectionChanged(SelectionChangedEventArgs e) { @@ -881,7 +850,6 @@ private async Task ReloadItemIconsAsync() var shellViewModel = parentShellPage.GetRequiredShellViewModel(); shellViewModel.CancelExtendedPropertiesLoading(); -#if !WINDOWS var request = ++iconReloadRequest; // Finish realizing the new panel before loading its icons; recycling cancels per-item loads. await DispatcherQueue.EnqueueAsync(() => FileList.UpdateLayout(), Microsoft.UI.Dispatching.DispatcherQueuePriority.Low); @@ -893,20 +861,13 @@ private async Task ReloadItemIconsAsync() .Select(container => container.Content) .OfType() .ToHashSet() ?? []; -#endif var filesAndFolders = shellViewModel.FilesAndFolders.ToList(); foreach (ListedItem listedItem in filesAndFolders) { -#if !WINDOWS if (request != iconReloadRequest) return; -#endif listedItem.ItemPropertiesInitialized = false; -#if WINDOWS - if (FileList.ContainerFromItem(listedItem) is not null) -#else if (realizedItems.Contains(listedItem)) -#endif await shellViewModel.LoadExtendedItemPropertiesAsync(listedItem); } @@ -1133,7 +1094,6 @@ private void SetCheckboxSelectionState(object item, GridViewItem? lviContainer = [DynamicWindowsRuntimeCast(typeof(GridViewItem))] private void Grid_Loaded(object sender, RoutedEventArgs e) { -#if !WINDOWS var root = (Grid)sender; if (root.DataContext is ListedItem listedItem) { @@ -1143,7 +1103,6 @@ private void Grid_Loaded(object sender, RoutedEventArgs e) _ = ParentShellPageInstance?.ShellViewModel?.LoadExtendedItemPropertiesAsync(listedItem); }); } -#endif // This is the best way I could find to set the context flyout, as doing it in the styles isn't possible // because you can't use bindings in the setters DependencyObject item = VisualTreeHelper.GetParent(sender as Grid); diff --git a/src/Files.App/Views/Layouts/LinuxGroupedItemsSource.cs b/src/Files.App/Views/Layouts/LinuxGroupedItemsSource.cs index 31644b4f7f2f..0264a6e6cf9c 100644 --- a/src/Files.App/Views/Layouts/LinuxGroupedItemsSource.cs +++ b/src/Files.App/Views/Layouts/LinuxGroupedItemsSource.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; @@ -174,4 +173,3 @@ public void Dispose() } } } -#endif diff --git a/src/Files.App/Views/Layouts/LinuxGroupedWrapPanel.cs b/src/Files.App/Views/Layouts/LinuxGroupedWrapPanel.cs index ead7d7f94dc4..8f2a638948fd 100644 --- a/src/Files.App/Views/Layouts/LinuxGroupedWrapPanel.cs +++ b/src/Files.App/Views/Layouts/LinuxGroupedWrapPanel.cs @@ -1,7 +1,6 @@ // Copyright (c) Files Community // Licensed under the MIT License. -#if !WINDOWS using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Windows.Foundation; @@ -114,4 +113,3 @@ private Size Layout(Size size, bool arrange) } } } -#endif diff --git a/src/Files.App/Views/MainPage.xaml.cs b/src/Files.App/Views/MainPage.xaml.cs index 448adcc21da6..58e2d748ab90 100644 --- a/src/Files.App/Views/MainPage.xaml.cs +++ b/src/Files.App/Views/MainPage.xaml.cs @@ -15,10 +15,6 @@ using Windows.Foundation.Metadata; using Windows.Graphics; using Windows.UI.Input; -#if WINDOWS -using Windows.Win32; -using Windows.Win32.Foundation; -#endif using WinRT; using GridSplitter = Files.App.Controls.GridSplitter; using VirtualKey = Windows.System.VirtualKey; @@ -35,16 +31,10 @@ public sealed partial class MainPage : Page public SidebarViewModel SidebarAdaptiveViewModel { get; } public MainPageViewModel ViewModel { get; } -#if WINDOWS - private const int HTCAPTION = 2; -#endif private bool keyReleased = true; private DispatcherQueueTimer _updateDateDisplayTimer; -#if WINDOWS - private WindowMessageMonitor? _titleBarMessageMonitor; -#endif private readonly Dictionary _sidebarScrollByTab = new(); private TabBarItem? _previousSidebarTab; @@ -54,7 +44,6 @@ public MainPage() { InitializeComponent(); -#if !WINDOWS // Uno never invokes the Control.OnPreviewKeyDown/OnPreviewKeyUp/OnLostFocus virtuals, so none of the // hotkeys (ctrl+l, ctrl+t, alt+left, ...) fired on Linux. The routed events are raised, so hook those. PreviewKeyDown += async (_, e) => @@ -68,7 +57,6 @@ public MainPage() // Keeps content clear of the right-edge resize grip RootGrid.Padding = new(0, 0, 8, 8); -#endif // Dependency Injection UserSettingsService = Ioc.Default.GetRequiredService(); @@ -78,10 +66,6 @@ public MainPage() if (AppLanguageHelper.IsPreferredLanguageRtl) { -#if WINDOWS - if (OperatingSystem.IsWindows()) - Win32Helper.EnableRtlLayout(MainWindow.Instance.WindowHandle); -#endif FlowDirection = FlowDirection.RightToLeft; } @@ -96,12 +80,6 @@ public MainPage() ApplySidebarWidthState(); -#if WINDOWS - // Realize the navigation controls before the first measure pass. - FindName(nameof(InnerNavigationToolbar)); - FindName(nameof(TabControl)); - FindName(nameof(NavToolbar)); -#endif } private void NumberedTabKeyboardAccelerator_Invoked(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs e) @@ -168,40 +146,9 @@ private int SetTitleBarDragRegion(InputNonClientPointerSource source, SizeInt32 var height = (int)TabControl.ActualHeight; source.SetRegionRects(NonClientRegionKind.Passthrough, [getScaledRect(this, new RectInt32 { X = 0, Y = 0, Width = (int)(TabControl.ActualWidth + TabControl.Margin.Left - TabControl.DragArea.ActualWidth), Height = height })]); -#if WINDOWS - AttachTitleBarMessageMonitor(); -#endif return height; } -#if WINDOWS - // Caption regions live in a dedicated child window - private void AttachTitleBarMessageMonitor() - { - if (!OperatingSystem.IsWindows() || _titleBarMessageMonitor is not null) - return; - - var titleBarHwnd = PInvoke.FindWindowEx(new(MainWindow.Instance.WindowHandle), HWND.Null, "InputNonClientPointerSource", null); - if (titleBarHwnd.IsNull) - return; - - _titleBarMessageMonitor = new WindowMessageMonitor(titleBarHwnd); - _titleBarMessageMonitor.WindowMessageReceived += TitleBar_WindowMessageReceived; - } - - private void TitleBar_WindowMessageReceived(object? sender, WindowMessageEventArgs e) - { - if (e.Message.MessageId is not (PInvoke.WM_NCMBUTTONDOWN or PInvoke.WM_NCMBUTTONDBLCLK) || - (int)e.Message.WParam != HTCAPTION || TabControl is null) - return; - - // Deferred because this runs inside the window procedure - DispatcherQueue.TryEnqueue(async () => await Commands.NewTab.ExecuteAsync()); - - e.Result = 0; - e.Handled = true; - } -#endif public async void TabItemContent_ContentChanged(object? sender, TabBarItemParameter e) { @@ -364,12 +311,10 @@ protected override void OnLostFocus(RoutedEventArgs e) private void Page_Loaded(object sender, RoutedEventArgs e) { ViewModel.OnPageLoaded(); -#if !WINDOWS // LINUX-TODO(toolbar): realizing x:Load controls in the constructor leaves their x:Bind bindings uninitialized on Uno (toolbar row never shows), so defer to Loaded. FindName(nameof(InnerNavigationToolbar)); FindName(nameof(TabControl)); FindName(nameof(NavToolbar)); -#endif MainWindow.Instance.AppWindow.Changed += (_, _) => MainWindow.Instance.RaiseSetTitleBarDragRegion(SetTitleBarDragRegion); diff --git a/src/Files.App/Views/Properties/CompatibilityPage.xaml b/src/Files.App/Views/Properties/CompatibilityPage.xaml deleted file mode 100644 index fd5b860a6d41..000000000000 --- a/src/Files.App/Views/Properties/CompatibilityPage.xaml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Files.App/Views/Properties/CompatibilityPage.xaml.cs b/src/Files.App/Views/Properties/CompatibilityPage.xaml.cs deleted file mode 100644 index 0134b6a391ee..000000000000 --- a/src/Files.App/Views/Properties/CompatibilityPage.xaml.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Properties; -using Microsoft.UI.Xaml.Navigation; - -namespace Files.App.Views.Properties -{ - public sealed partial class CompatibilityPage : BasePropertiesPage - { - private CompatibilityViewModel? CompatibilityViewModel { get; set; } - - public CompatibilityPage() - { - InitializeComponent(); - } - - protected override void OnNavigatedTo(NavigationEventArgs e) - { - var np = (PropertiesPageNavigationParameter)e.Parameter; - if (np.Parameter is ListedItem listedItem) - CompatibilityViewModel = new CompatibilityViewModel(listedItem); - - base.OnNavigatedTo(e); - } - - public override Task SaveChangesAsync() - { - if (CompatibilityViewModel is not null) - return Task.FromResult(CompatibilityViewModel.SetCompatibilityOptions()); - - return Task.FromResult(false); - } - - public override void Dispose() - { - } - } -} diff --git a/src/Files.App/Views/Properties/CustomizationPage.xaml b/src/Files.App/Views/Properties/CustomizationPage.xaml deleted file mode 100644 index d2cc11b52b31..000000000000 --- a/src/Files.App/Views/Properties/CustomizationPage.xaml +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Files.App/Views/Properties/SecurityAdvancedPage.xaml.cs b/src/Files.App/Views/Properties/SecurityAdvancedPage.xaml.cs deleted file mode 100644 index d03a922ab966..000000000000 --- a/src/Files.App/Views/Properties/SecurityAdvancedPage.xaml.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Properties; -using Microsoft.UI.Xaml.Navigation; - -namespace Files.App.Views.Properties -{ - public sealed partial class SecurityAdvancedPage : BasePropertiesPage - { - private SecurityAdvancedViewModel? SecurityAdvancedViewModel { get; set; } - - public SecurityAdvancedPage() - { - InitializeComponent(); - } - - protected override void OnNavigatedTo(NavigationEventArgs e) - { - var parameter = (PropertiesPageNavigationParameter)e.Parameter; - SecurityAdvancedViewModel = new(parameter); - - base.OnNavigatedTo(e); - } - - public async override Task SaveChangesAsync() - => await Task.FromResult(true); - - public override void Dispose() - { - } - } -} diff --git a/src/Files.App/Views/Properties/SecurityPage.xaml b/src/Files.App/Views/Properties/SecurityPage.xaml deleted file mode 100644 index 4e597bda7c98..000000000000 --- a/src/Files.App/Views/Properties/SecurityPage.xaml +++ /dev/null @@ -1,454 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Files.App/Views/Properties/SecurityPage.xaml.cs b/src/Files.App/Views/Properties/SecurityPage.xaml.cs deleted file mode 100644 index 12079cc6219e..000000000000 --- a/src/Files.App/Views/Properties/SecurityPage.xaml.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Files Community -// Licensed under the MIT License. - -using Files.App.ViewModels.Properties; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Navigation; - -namespace Files.App.Views.Properties -{ - public sealed partial class SecurityPage : BasePropertiesPage - { - private SecurityViewModel SecurityViewModel { get; set; } = null!; - - private PropertiesPageNavigationParameter _parameter = null!; - - public SecurityPage() - { - InitializeComponent(); - } - - protected override void OnNavigatedTo(NavigationEventArgs e) - { - var parameter = (PropertiesPageNavigationParameter)e.Parameter; - SecurityViewModel = new(parameter); - - _parameter = parameter; - - base.OnNavigatedTo(e); - } - - private void OpenSecurityAdvancedPageButton_Click(object sender, RoutedEventArgs e) - { - Frame?.Navigate(typeof(SecurityAdvancedPage), _parameter); - } - - public async override Task SaveChangesAsync() - => await Task.FromResult(true); - - public override void Dispose() - { - } - } -} diff --git a/src/Files.App/Views/Properties/SignaturesPage.xaml b/src/Files.App/Views/Properties/SignaturesPage.xaml deleted file mode 100644 index da004b426507..000000000000 --- a/src/Files.App/Views/Properties/SignaturesPage.xaml +++ /dev/null @@ -1,210 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -