commit 2f835c9dee19514dbd6910dfd4a8444bda10fddd Author: BytexGrid Date: Wed Jan 1 17:54:24 2025 +0530 Release version 2.0.0 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..92237fa --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,43 @@ +--- +name: Bug report +about: Create a report to help us improve +title: BUGGGHH +labels: bug, good first issue, help wanted +assignees: BytexGrid + +--- + +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Do '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**System Information:** +- Windows Version: [e.g. Windows 10, Windows 11] +- NeatShift Version: [e.g. 1.0.0] +- .NET Runtime Version: [e.g. 6.0] + +**Additional context** +- Are you using any specific keyboard/mouse settings? +- Any relevant Windows settings (like High DPI, custom themes)? +- Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..f1bbe4c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: Feature +labels: enhancement, good first issue, help wanted +assignees: BytexGrid + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..89a5347 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,82 @@ +name: Release + +on: + push: + tags: + - "v*" + +permissions: + contents: write + packages: read # for package dependencies + actions: read # for checking out code + +jobs: + build: + runs-on: windows-latest + + steps: + - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 + + - name: Setup .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 6.0.x + + - name: Restore dependencies + working-directory: ./NeatShift + run: dotnet restore NeatShift.sln + + - name: Build + working-directory: ./NeatShift + run: dotnet build NeatShift.sln --configuration Release --no-restore + + - name: Publish + working-directory: ./NeatShift + run: | + dotnet publish "NeatShift/NeatShift.csproj" -c Release -r win-x64 ` + --self-contained true ` + -p:PublishSingleFile=true ` + -p:EnableCompressionInSingleFile=true ` + -p:IncludeNativeLibrariesForSelfExtract=true ` + -p:DebugType=None ` + -p:DebugSymbols=false ` + -p:PublishReadyToRun=true ` + -p:PublishTrimmed=false ` + -p:ApplicationManifest=app.manifest ` + -p:WindowsPackageType=None ` + -p:IncludeAllContentForSelfExtract=true ` + -o ../publish + + - name: Copy exe to release + run: Copy-Item "publish/NeatShift.exe" -Destination "NeatShift.exe" + + - name: Create Runtime Config + run: | + Set-Content -Path "publish/NeatShift.runtimeconfig.json" -Value '{ + "runtimeOptions": { + "tfm": "net6.0-windows", + "framework": { + "name": "Microsoft.WindowsDesktop.App", + "version": "6.0.0" + }, + "configProperties": { + "System.Reflection.Metadata.MetadataUpdater.IsSupported": false + } + } + }' + + - name: Zip Release with Config + run: Compress-Archive -Path "publish/*" -DestinationPath "NeatShift-Release.zip" + + - name: Create Release + uses: softprops/action-gh-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + files: | + NeatShift.exe + NeatShift-Release.zip + draft: false + prerelease: false + generate_release_notes: true + tag_name: ${{ github.ref_type == 'tag' && github.ref_name || 'v1.0.0' }} \ No newline at end of file diff --git a/.github/workflows/wiki.yml b/.github/workflows/wiki.yml new file mode 100644 index 0000000..a27c4de --- /dev/null +++ b/.github/workflows/wiki.yml @@ -0,0 +1,30 @@ +name: Update Wiki + +on: + push: + branches: + - main + paths: + - 'wiki/**' + + +permissions: + contents: read + pages: write + + +jobs: + update-wiki: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + with: + fetch-depth: 0 + + - name: Upload Wiki Content + uses: SwiftDocOrg/github-wiki-publish-action@98d0d21e4c8f4d7c7bef2e2dc8449b4c4c888878 + with: + path: "wiki" + env: + GH_PERSONAL_ACCESS_TOKEN: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d7e1155 --- /dev/null +++ b/.gitignore @@ -0,0 +1,134 @@ +## .NET Core +bin/ +obj/ +/packages/ +runtimes/ + +## Visual Studio +.vs/ +*.user +*.userosscache +*.sln.docstates +*.userprefs + +## Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +## Visual Studio cache/options directory +.vs/ + +## MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +## NUNIT +*.VisualState.xml +TestResult.xml + +## Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +## .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +## Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +## Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +## Visual Studio Code +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +## ReSharper +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +## Development files +DEVELOPMENT_LOG.md + +## NuGet +packages/ +*.nupkg +*.snupkg + +## User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +## Windows image file caches +Thumbs.db +ehthumbs.db + +## Folder config file +Desktop.ini + +## Recycle Bin used on file shares +$RECYCLE.BIN/ + +## VS Code directories +.vscode/ + +## Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +## Windows shortcuts +*.lnk \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..fdd46c5 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +neatshiftcontact@zohomail.in. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..268feba --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,95 @@ +# Contributing to NeatShift + +Hey there! Thanks for considering contributing to NeatShift. Whether you're fixing bugs, adding features, or improving documentation, your help makes NeatShift better for everyone. + +## Branch Strategy + +We use a two-branch system: +- `main` - stable branch for releases +- `develop` - branch for active development and contributions + +Always create your changes in `develop`, not `main`! + +## Quick Start + +1. Fork the repo +2. Clone your fork: `git clone https://github.com/your-username/NeatShift.git` +3. Create your feature branch from `develop`: `git checkout develop && git checkout -b cool-new-feature` +4. Make your changes +5. Test your changes +6. Commit: `git commit -m 'Add some feature'` +7. Push: `git push origin cool-new-feature` +8. Open a Pull Request targeting the `develop` branch + +## Development Setup + +1. Make sure you have .NET 6.0 SDK installed +2. Open the solution in Visual Studio 2022 or your preferred IDE +3. Restore NuGet packages +4. Build and run! + +## What Can I Work On? + +- Check out our [open issues](https://github.com/BytexGrid/NeatShift/issues) +- Look for issues tagged with `good-first-issue` if you're just starting +- Feel free to propose new features through issues + +## Code Style + +We keep it simple: +- Use standard C# naming conventions +- Keep methods focused and small +- Add comments for non-obvious code +- Include XML documentation for public APIs + +## Making Changes + +1. **Always Branch from Develop**: Your changes should be based on the `develop` branch +2. **Keep Changes Small**: Smaller PRs are easier to review +3. **Write Good Commit Messages**: Explain what and why, not how +4. **Update Documentation**: If you change functionality, update the docs +5. **Add Tests**: New features should include tests +6. **Test Your Changes**: Make sure everything still works! + +## Pull Request Process + +1. Make sure your PR targets the `develop` branch +2. Update the README.md if needed +3. Make sure your code builds clean without warnings +4. Write a good PR description explaining: + - What you changed + - Why you changed it + - How to test it +5. Link any related issues + +## Need Help? + +- Check out our [documentation](https://github.com/BytexGrid/NeatShift/wiki) +- Create an issue with your question +- Join our discussions + +## Bug Reports + +Found a bug? Please include: +- Steps to reproduce +- What you expected to happen +- What actually happened +- Screenshots if relevant +- Your environment (OS, .NET version, etc.) + +## Feature Requests + +Have an idea? Great! Create an issue and: +- Explain the feature +- Why it would be useful +- How it should work +- Any implementation ideas you have + +## Code Review Process + +1. At least one maintainer will review your PR +2. We might suggest changes +3. Once approved, it will be merged into `develop` +4. Changes in `develop` will be periodically merged to `main` for releases + +Thanks for contributing to NeatShift! 🚀 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NeatShift/.gitattributes b/NeatShift/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/NeatShift/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/NeatShift/.gitignore b/NeatShift/.gitignore new file mode 100644 index 0000000..159b041 --- /dev/null +++ b/NeatShift/.gitignore @@ -0,0 +1,247 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +[Xx]64/ +[Xx]86/ +[Bb]uild/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml + +# TODO: Un-comment the next line if you do not want to checkin +# your web deploy settings because they may include unencrypted +# passwords +#*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Microsoft Azure ApplicationInsights config file +ApplicationInsights.config + +# Windows Store app package directory +AppPackages/ +BundleArtifacts/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# LightSwitch generated files +GeneratedArtifacts/ +ModelManifest.xml + +# Paket dependency manager +.paket/paket.exe + +# FAKE - F# Make +.fake/ +/Icon/Thumbs.db +/Icon/Thumbs.db diff --git a/NeatShift/Icon/icon.png b/NeatShift/Icon/icon.png new file mode 100644 index 0000000..79dbec9 Binary files /dev/null and b/NeatShift/Icon/icon.png differ diff --git a/NeatShift/LICENSE.txt b/NeatShift/LICENSE.txt new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/NeatShift/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/NeatShift/NeatShift.sln b/NeatShift/NeatShift.sln new file mode 100644 index 0000000..c90311b --- /dev/null +++ b/NeatShift/NeatShift.sln @@ -0,0 +1,21 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NeatShift", "NeatShift\NeatShift.csproj", "{8DBA430E-C60B-45CD-8A07-814D10FB70AB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8DBA430E-C60B-45CD-8A07-814D10FB70AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8DBA430E-C60B-45CD-8A07-814D10FB70AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8DBA430E-C60B-45CD-8A07-814D10FB70AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8DBA430E-C60B-45CD-8A07-814D10FB70AB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/NeatShift/NeatShift/App.config b/NeatShift/NeatShift/App.config new file mode 100644 index 0000000..ecdcf8a --- /dev/null +++ b/NeatShift/NeatShift/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/NeatShift/NeatShift/App.xaml b/NeatShift/NeatShift/App.xaml new file mode 100644 index 0000000..0d50c30 --- /dev/null +++ b/NeatShift/NeatShift/App.xaml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NeatShift/NeatShift/App.xaml.cs b/NeatShift/NeatShift/App.xaml.cs new file mode 100644 index 0000000..b43e9ee --- /dev/null +++ b/NeatShift/NeatShift/App.xaml.cs @@ -0,0 +1,93 @@ +using Microsoft.Extensions.DependencyInjection; +using ModernWpf; +using NeatShift.Services; +using NeatShift.ViewModels; +using NeatShift.Views; +using NeatShift.Models; +using System; +using System.Diagnostics; +using System.Runtime.Versioning; +using System.Security.Principal; +using System.Windows; + +namespace NeatShift +{ + [SupportedOSPlatform("windows7.0")] + public partial class App : Application + { + private ServiceProvider? _serviceProvider; + public IServiceProvider Services => _serviceProvider ?? throw new InvalidOperationException("Services not initialized"); + + [SupportedOSPlatform("windows7.0")] + protected override void OnStartup(StartupEventArgs e) + { + // Check if running as administrator + bool isAdmin = IsRunningAsAdministrator(); + if (!isAdmin) + { + // Restart the application with admin rights + try + { + var processInfo = new ProcessStartInfo + { + UseShellExecute = true, + FileName = Process.GetCurrentProcess().MainModule?.FileName, + Verb = "runas" + }; + + Process.Start(processInfo); + Current.Shutdown(); + return; + } + catch (Exception ex) + { + MessageBox.Show($"Failed to restart with administrator privileges: {ex.Message}", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + } + + var services = new ServiceCollection(); + + ConfigureServices(services); + + _serviceProvider = services.BuildServiceProvider(); + + var mainWindow = new MainWindow(_serviceProvider.GetRequiredService()); + mainWindow.Show(); + } + + [SupportedOSPlatform("windows")] + private static bool IsRunningAsAdministrator() + { + var identity = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(identity); + return principal.IsInRole(WindowsBuiltInRole.Administrator); + } + + [SupportedOSPlatform("windows7.0")] + private void ConfigureServices(IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(provider => + { + var settingsService = provider.GetRequiredService(); + var settings = new NeatSavesSettings + { + UseNeatSaves = settingsService.GetUseNeatSaves(), + MaxOperationsToKeep = settingsService.GetMaxNeatSaves(), + SaveLocation = settingsService.GetNeatSavesLocation() + }; + return new NeatSavesService(settings); + }); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => new MainWindow(sp.GetRequiredService())); + services.AddHttpClient(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Converters/BooleanToNumberConverter.cs b/NeatShift/NeatShift/Converters/BooleanToNumberConverter.cs new file mode 100644 index 0000000..b9d8ed0 --- /dev/null +++ b/NeatShift/NeatShift/Converters/BooleanToNumberConverter.cs @@ -0,0 +1,19 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace NeatShift.Converters +{ + public class BooleanToNumberConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? 0 : 1; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (int)value == 0; + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Converters/CountToVisibilityConverter.cs b/NeatShift/NeatShift/Converters/CountToVisibilityConverter.cs new file mode 100644 index 0000000..7c85a10 --- /dev/null +++ b/NeatShift/NeatShift/Converters/CountToVisibilityConverter.cs @@ -0,0 +1,24 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace NeatShift.Converters +{ + public class CountToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is int count) + { + return count == 0 ? Visibility.Visible : Visibility.Collapsed; + } + return Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Converters/FileTypeToSymbolConverter.cs b/NeatShift/NeatShift/Converters/FileTypeToSymbolConverter.cs new file mode 100644 index 0000000..3dbd406 --- /dev/null +++ b/NeatShift/NeatShift/Converters/FileTypeToSymbolConverter.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; +using System.Runtime.Versioning; +using System.Windows.Data; +using ModernWpf.Controls; + +namespace NeatShift.Converters +{ + [SupportedOSPlatform("windows7.0")] + public class FileTypeToSymbolConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool isDirectory) + { + return isDirectory ? Symbol.Folder : Symbol.Document; + } + return Symbol.Document; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Models/FileSystemItem.cs b/NeatShift/NeatShift/Models/FileSystemItem.cs new file mode 100644 index 0000000..a0e4c2e --- /dev/null +++ b/NeatShift/NeatShift/Models/FileSystemItem.cs @@ -0,0 +1,28 @@ +using System.IO; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace NeatShift.Models +{ + public partial class FileSystemItem : ObservableObject + { + [ObservableProperty] + private string _name = string.Empty; + + [ObservableProperty] + private string _path = string.Empty; + + [ObservableProperty] + private bool _isDirectory; + + public FileSystemItem() + { + } + + public FileSystemItem(string path) + { + Path = path; + Name = System.IO.Path.GetFileName(path); + IsDirectory = Directory.Exists(path); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Models/NeatSavesOperation.cs b/NeatShift/NeatShift/Models/NeatSavesOperation.cs new file mode 100644 index 0000000..9015512 --- /dev/null +++ b/NeatShift/NeatShift/Models/NeatSavesOperation.cs @@ -0,0 +1,15 @@ +using System; + +namespace NeatShift.Models +{ + public class NeatSavesOperation + { + public string Id { get; set; } = Guid.NewGuid().ToString(); + public string Description { get; set; } = string.Empty; + public DateTime CreationTime { get; set; } = DateTime.Now; + public string SourcePath { get; set; } = string.Empty; + public string DestinationPath { get; set; } = string.Empty; + public bool IsSymbolicLinkCreated { get; set; } + public bool IsRestorePointCreated { get; set; } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Models/NeatSavesSettings.cs b/NeatShift/NeatShift/Models/NeatSavesSettings.cs new file mode 100644 index 0000000..b24a3ed --- /dev/null +++ b/NeatShift/NeatShift/Models/NeatSavesSettings.cs @@ -0,0 +1,16 @@ +using System; +using System.IO; + +namespace NeatShift.Models +{ + public class NeatSavesSettings + { + public bool UseNeatSaves { get; set; } = false; + public int MaxOperationsToKeep { get; set; } = 50; + public string SaveLocation { get; set; } = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "NeatShift", + "NeatSaves" + ); + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Models/RestorePoint.cs b/NeatShift/NeatShift/Models/RestorePoint.cs new file mode 100644 index 0000000..ff58cf4 --- /dev/null +++ b/NeatShift/NeatShift/Models/RestorePoint.cs @@ -0,0 +1,11 @@ +using System; + +namespace NeatShift.Models +{ + public class RestorePoint + { + public string Description { get; set; } = string.Empty; + public DateTime CreationTime { get; set; } + public string Id { get; set; } = Guid.NewGuid().ToString(); + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Models/Settings.cs b/NeatShift/NeatShift/Models/Settings.cs new file mode 100644 index 0000000..7dc0ea8 --- /dev/null +++ b/NeatShift/NeatShift/Models/Settings.cs @@ -0,0 +1,144 @@ +using System; +using System.IO; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Windows.Input; +using Microsoft.Win32; +using ModernWpf.Controls; +using System.Windows; +using Microsoft.WindowsAPICodePack.Dialogs; +using CommunityToolkit.Mvvm.Input; + +namespace NeatShift.Models +{ + public class Settings : INotifyPropertyChanged + { + private bool _createRestorePoint = true; + private bool _hideSymbolicLinks = true; + private string _lastUsedPath = string.Empty; + private bool _useNeatSaves = false; + private int _maxNeatSaves = 50; + private string _neatSavesLocation = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + "NeatShift", + "NeatSaves" + ); + private bool _hasShownSafetyChoice = false; + + private ICommand? _browseNeatSavesLocationCommand; + public ICommand BrowseNeatSavesLocationCommand => _browseNeatSavesLocationCommand ??= new RelayCommand(BrowseNeatSavesLocation); + + private void BrowseNeatSavesLocation() + { + var dialog = new CommonOpenFileDialog + { + Title = "Select NeatSaves Location", + IsFolderPicker = true, + InitialDirectory = NeatSavesLocation + }; + + if (dialog.ShowDialog() == CommonFileDialogResult.Ok) + { + NeatSavesLocation = dialog.FileName; + } + } + + public event PropertyChangedEventHandler? PropertyChanged; + + protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName ?? string.Empty)); + } + + public bool CreateRestorePoint + { + get => _createRestorePoint; + set + { + if (_createRestorePoint != value) + { + _createRestorePoint = value; + OnPropertyChanged(); + } + } + } + + public bool HideSymbolicLinks + { + get => _hideSymbolicLinks; + set + { + if (_hideSymbolicLinks != value) + { + _hideSymbolicLinks = value; + OnPropertyChanged(); + } + } + } + + public string LastUsedPath + { + get => _lastUsedPath; + set + { + if (_lastUsedPath != value) + { + _lastUsedPath = value; + OnPropertyChanged(); + } + } + } + + public bool UseNeatSaves + { + get => _useNeatSaves; + set + { + if (_useNeatSaves != value) + { + _useNeatSaves = value; + OnPropertyChanged(); + } + } + } + + public int MaxNeatSaves + { + get => _maxNeatSaves; + set + { + if (_maxNeatSaves != value) + { + _maxNeatSaves = value; + OnPropertyChanged(); + } + } + } + + public string NeatSavesLocation + { + get => _neatSavesLocation; + set + { + if (_neatSavesLocation != value) + { + _neatSavesLocation = value; + OnPropertyChanged(); + } + } + } + + public bool HasShownSafetyChoice + { + get => _hasShownSafetyChoice; + set + { + if (_hasShownSafetyChoice != value) + { + _hasShownSafetyChoice = value; + OnPropertyChanged(); + } + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/NeatShift.csproj b/NeatShift/NeatShift/NeatShift.csproj new file mode 100644 index 0000000..a1b41c8 --- /dev/null +++ b/NeatShift/NeatShift/NeatShift.csproj @@ -0,0 +1,50 @@ + + + + + WinExe + net8.0-windows10.0.17763.0 + enable + true + true + icon.ico + app.manifest + 2.0.0 + BytexGrid + BytexGrid + NeatShift + File and folder organization tool with symbolic link support + Copyright © 2024 BytexGrid + false + true + true + win-x64 + 10.0.17763.0 + true + PerMonitorV2 + + + + + + + + + + + + + + + + PreserveNewest + + + + + + Always + + + + \ No newline at end of file diff --git a/NeatShift/NeatShift/ProgressDialog.Designer.cs b/NeatShift/NeatShift/ProgressDialog.Designer.cs new file mode 100644 index 0000000..4ca69f2 --- /dev/null +++ b/NeatShift/NeatShift/ProgressDialog.Designer.cs @@ -0,0 +1,102 @@ +using System; +using System.Windows.Forms; + +namespace NeatShift +{ + partial class ProgressDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.progressBar1 = new System.Windows.Forms.ProgressBar(); + this.label_Message = new System.Windows.Forms.Label(); + this.button_Cancel = new System.Windows.Forms.Button(); + this.label_Progress = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // progressBar1 + // + this.progressBar1.Location = new System.Drawing.Point(12, 25); + this.progressBar1.Name = "progressBar1"; + this.progressBar1.Size = new System.Drawing.Size(360, 23); + this.progressBar1.TabIndex = 0; + // + // label_Message + // + this.label_Message.AutoSize = true; + this.label_Message.Location = new System.Drawing.Point(12, 9); + this.label_Message.Name = "label_Message"; + this.label_Message.Size = new System.Drawing.Size(50, 13); + this.label_Message.TabIndex = 1; + this.label_Message.Text = "Message"; + // + // button_Cancel + // + this.button_Cancel.Location = new System.Drawing.Point(297, 54); + this.button_Cancel.Name = "button_Cancel"; + this.button_Cancel.Size = new System.Drawing.Size(75, 23); + this.button_Cancel.TabIndex = 2; + this.button_Cancel.Text = "Cancel"; + this.button_Cancel.UseVisualStyleBackColor = true; + // + // label_Progress + // + this.label_Progress.AutoSize = true; + this.label_Progress.Location = new System.Drawing.Point(12, 59); + this.label_Progress.Name = "label_Progress"; + this.label_Progress.Size = new System.Drawing.Size(48, 13); + this.label_Progress.TabIndex = 3; + this.label_Progress.Text = "Progress"; + // + // ProgressDialog + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(384, 89); + this.Controls.Add(this.label_Progress); + this.Controls.Add(this.button_Cancel); + this.Controls.Add(this.label_Message); + this.Controls.Add(this.progressBar1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ProgressDialog"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Progress"; + this.ResumeLayout(false); + this.PerformLayout(); + } + + #endregion + + private System.Windows.Forms.ProgressBar progressBar1; + private System.Windows.Forms.Label label_Message; + private System.Windows.Forms.Button button_Cancel; + private System.Windows.Forms.Label label_Progress; + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/ProgressDialog.cs b/NeatShift/NeatShift/ProgressDialog.cs new file mode 100644 index 0000000..a7c6fb5 --- /dev/null +++ b/NeatShift/NeatShift/ProgressDialog.cs @@ -0,0 +1,73 @@ +// FreeMove -- Move directories without breaking shortcuts or installations +// Copyright(C) 2020 Luca De Martini + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program.If not, see. + +using System; +using System.Windows.Forms; +using NeatShift.Services; + +namespace NeatShift +{ + public partial class ProgressDialog : Form + { + private readonly IOOperation _operation; + + public ProgressDialog(IOOperation operation) + { + InitializeComponent(); + _operation = operation; + + _operation.ProgressChanged += Operation_ProgressChanged; + _operation.Completed += Operation_Completed; + _operation.Cancelled += Operation_Cancelled; + + button_Cancel.Click += (s, e) => _operation.Cancel(); + } + + private void Operation_ProgressChanged(object? sender, ProgressChangedEventArgs e) + { + if (InvokeRequired) + { + Invoke(new Action(() => Operation_ProgressChanged(sender, e))); + return; + } + + progressBar1.Value = e.ProgressPercentage; + label_Progress.Text = e.Message; + } + + private void Operation_Completed(object? sender, EventArgs e) + { + if (InvokeRequired) + { + Invoke(new Action(() => Operation_Completed(sender, e))); + return; + } + + Close(); + } + + private void Operation_Cancelled(object? sender, EventArgs e) + { + if (InvokeRequired) + { + Invoke(new Action(() => Operation_Cancelled(sender, e))); + return; + } + + Close(); + } + } +} diff --git a/NeatShift/NeatShift/ProgressDialog.resx b/NeatShift/NeatShift/ProgressDialog.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/NeatShift/NeatShift/ProgressDialog.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/NeatShift/NeatShift/Properties/AssemblyInfo.cs b/NeatShift/NeatShift/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c5b4f37 --- /dev/null +++ b/NeatShift/NeatShift/Properties/AssemblyInfo.cs @@ -0,0 +1,42 @@ +// NeatShift -- Organize files and folders with symbolic links +// Copyright(C) 2024 + +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled by the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("NeatShift")] +[assembly: AssemblyDescription("File organization tool with symbolic link support")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("BytexGrid")] +[assembly: AssemblyProduct("NeatShift")] +[assembly: AssemblyCopyright("Copyright © 2024 BytexGrid")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8dba430e-c60b-45cd-8a07-814d10fb70ab")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] + +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] + +[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] \ No newline at end of file diff --git a/NeatShift/NeatShift/Properties/GlobalSuppressions.cs b/NeatShift/NeatShift/Properties/GlobalSuppressions.cs new file mode 100644 index 0000000..39b0228 --- /dev/null +++ b/NeatShift/NeatShift/Properties/GlobalSuppressions.cs @@ -0,0 +1,4 @@ +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", + Justification = "This application is designed for Windows only and requires Windows 7.0 or later.")] \ No newline at end of file diff --git a/NeatShift/NeatShift/Properties/Resources.Designer.cs b/NeatShift/NeatShift/Properties/Resources.Designer.cs new file mode 100644 index 0000000..61be8cf --- /dev/null +++ b/NeatShift/NeatShift/Properties/Resources.Designer.cs @@ -0,0 +1,177 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace FreeMove.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FreeMove.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to imDema/FreeMove {0} -- Move directories without breaking shortcuts or installations + ///Copyright(C) 2020 Luca De Martini + /// + ///This program is free software: you can redistribute it and/or modify + ///it under the terms of the GNU General Public License as published by + ///the Free Software Foundation, either version 3 of the License, or + ///(at your option) any later version. + /// + ///This program is distributed in the hope that it will be useful, + ///but WITHOUT ANY WARRANTY; without even the implied warranty of + ///MERCHANTABILI [rest of string was truncated]";. + /// + internal static string AboutContent { + get { + return ResourceManager.GetString("AboutContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to It's strongly recommended not to move the "Program Files" or the "Program Files (x86)" directories as it can lead to unexpexted behaviour. + ///You are free to move any of the programs contained in those directories without any problem instead. + /// + ///Are you sure you want to disable safe mode?. + /// + internal static string DisableSafeModeMessage { + get { + return ResourceManager.GetString("DisableSafeModeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ERROR creating symbolic link. + ///The folder is in the new position but the link could not be created. + ///Try running as administrator + /// + ///Do you want to move the files back?. + /// + internal static string ErrorUnauthorizedLink { + get { + return ResourceManager.GetString("ErrorUnauthorizedLink", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The error was caused by a file which couldn't be moved, it may be in use or you may not have the required permissions. + /// + ///Try running this program as administrator and/or close any program that is using the file specified in the details + /// + ///DETAILS:. + /// + internal static string ErrorUnauthorizedMoveDetails { + get { + return ResourceManager.GetString("ErrorUnauthorizedMoveDetails", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error: {0} + /// + ///How do you want to proceed? + ///"Abort" to revert changes + ///"Ignore" to stop the program. + /// + internal static string ErrorUnauthorizedMoveMessage { + get { + return ResourceManager.GetString("ErrorUnauthorizedMoveMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not retrieve the version information + ///from the GitHub server. + /// + internal static string GitHubErrorMessage { + get { + return ResourceManager.GetString("GitHubErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to proceed? + /// + ///By ignoring you will leave all the files as they are now: part of the files will already be in the new location and missing from the old one!. + /// + internal static string IgnoreMessage { + get { + return ResourceManager.GetString("IgnoreMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error when moving the files using FreeMove on {0} and you chose to ignore it. + ///The rest of the contents of this directory can be found at "{1}" unless they were moved. + ///Next time use "Abort" in case of an error to move the files back or "Retry" to try again. + /// + ///If this text file was useful or if you would have preferred it wasn't created let me know. + ///. + /// + internal static string IgnoreTextFile { + get { + return ResourceManager.GetString("IgnoreTextFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ImDema-FreeMove-Updater. + /// + internal static string UserAgent { + get { + return ResourceManager.GetString("UserAgent", resourceCulture); + } + } + } +} diff --git a/NeatShift/NeatShift/Properties/Resources.resx b/NeatShift/NeatShift/Properties/Resources.resx new file mode 100644 index 0000000..f52b321 --- /dev/null +++ b/NeatShift/NeatShift/Properties/Resources.resx @@ -0,0 +1,186 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + imDema/FreeMove {0} -- Move directories without breaking shortcuts or installations +Copyright(C) 2020 Luca De Martini + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program.If not, see<http://www.gnu.org/licenses/>. + +https://github.com/imDema + + + It's strongly recommended not to move the "Program Files" or the "Program Files (x86)" directories as it can lead to unexpexted behaviour. +You are free to move any of the programs contained in those directories without any problem instead. + +Are you sure you want to disable safe mode? + + + ERROR creating symbolic link. +The folder is in the new position but the link could not be created. +Try running as administrator + +Do you want to move the files back? + + + The error was caused by a file which couldn't be moved, it may be in use or you may not have the required permissions. + +Try running this program as administrator and/or close any program that is using the file specified in the details + +DETAILS: + + + Error: {0} + +How do you want to proceed? +"Abort" to revert changes +"Ignore" to stop the program + + + Could not retrieve the version information +from the GitHub server + + + Are you sure you want to proceed? + +By ignoring you will leave all the files as they are now: part of the files will already be in the new location and missing from the old one! + + + There was an error when moving the files using FreeMove on {0} and you chose to ignore it. +The rest of the contents of this directory can be found at "{1}" unless they were moved. +Next time use "Abort" in case of an error to move the files back or "Retry" to try again. + +If this text file was useful or if you would have preferred it wasn't created let me know. + + + + ImDema-FreeMove-Updater + + \ No newline at end of file diff --git a/NeatShift/NeatShift/Properties/Settings.Designer.cs b/NeatShift/NeatShift/Properties/Settings.Designer.cs new file mode 100644 index 0000000..84c6380 --- /dev/null +++ b/NeatShift/NeatShift/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace FreeMove.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.1.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/NeatShift/NeatShift/Properties/Settings.settings b/NeatShift/NeatShift/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/NeatShift/NeatShift/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/NeatShift/NeatShift/Services/FileOperationService.cs b/NeatShift/NeatShift/Services/FileOperationService.cs new file mode 100644 index 0000000..04d2eb6 --- /dev/null +++ b/NeatShift/NeatShift/Services/FileOperationService.cs @@ -0,0 +1,112 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using System.Diagnostics; + +namespace NeatShift.Services +{ + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public class FileOperationService : IFileOperationService + { + private readonly ISystemRestoreService _systemRestoreService; + private readonly ISettingsService _settingsService; + + public event EventHandler? ProgressChanged; + + public FileOperationService(ISystemRestoreService systemRestoreService, ISettingsService settingsService) + { + _systemRestoreService = systemRestoreService; + _settingsService = settingsService; + } + + public async Task MoveWithSymbolicLink(string sourcePath, string destinationPath) + { + try + { + OnProgressChanged(0, $"Preparing to move {Path.GetFileName(sourcePath)}..."); + + // Check if the destination already exists + if (File.Exists(destinationPath) || Directory.Exists(destinationPath)) + { + OnProgressChanged(0, "Error: A file or folder with the same name already exists in the destination."); + return false; + } + + if (_settingsService.GetCreateRestorePoint()) + { + OnProgressChanged(10, "Creating system restore point..."); + bool restorePointCreated = await _systemRestoreService.CreateRestorePoint("Before moving files"); + if (!restorePointCreated) + { + Debug.WriteLine("Failed to create restore point"); + OnProgressChanged(10, "Warning: Could not create system restore point. This may require administrator privileges."); + // Continue with the operation even if restore point creation fails + } + else + { + OnProgressChanged(20, "System restore point created successfully"); + } + } + + OnProgressChanged(30, "Moving files..."); + string? destinationDir = Path.GetDirectoryName(destinationPath); + if (string.IsNullOrEmpty(destinationDir)) + { + OnProgressChanged(0, "Error: Invalid destination path"); + return false; + } + + // Create destination directory if it doesn't exist + Directory.CreateDirectory(destinationDir); + + try + { + // Use Task.Run for potentially long-running file operations + await Task.Run(() => + { + if (Directory.Exists(sourcePath)) + { + Directory.Move(sourcePath, destinationPath); + } + else + { + File.Move(sourcePath, destinationPath); + } + }); + } + catch (IOException ex) when ((ex.HResult & 0x0000FFFF) == 183) // File already exists + { + OnProgressChanged(0, "Error: A file or folder with the same name already exists in the destination."); + return false; + } + + OnProgressChanged(60, "Creating symbolic link..."); + bool hideLink = _settingsService.GetHideSymbolicLinks(); + bool success = await Task.Run(() => IOHelper.CreateSymbolicLink(sourcePath, destinationPath, Directory.Exists(destinationPath), hideLink)); + + if (success) + { + OnProgressChanged(100, "Operation completed successfully"); + return true; + } + + OnProgressChanged(0, "Failed to create symbolic link. This may require administrator privileges."); + return false; + } + catch (Exception ex) + { + OnProgressChanged(0, $"Error: {ex.Message}"); + return false; + } + } + + protected virtual void OnProgressChanged(int progressPercentage, string message) + { + ProgressChanged?.Invoke(this, new ProgressChangedEventArgs + { + ProgressPercentage = progressPercentage, + Message = message + }); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/IFileOperationService.cs b/NeatShift/NeatShift/Services/IFileOperationService.cs new file mode 100644 index 0000000..e4b4582 --- /dev/null +++ b/NeatShift/NeatShift/Services/IFileOperationService.cs @@ -0,0 +1,17 @@ +using System; +using System.Threading.Tasks; + +namespace NeatShift.Services +{ + public interface IFileOperationService + { + event EventHandler ProgressChanged; + Task MoveWithSymbolicLink(string sourcePath, string destinationPath); + } + + public class ProgressChangedEventArgs : EventArgs + { + public int ProgressPercentage { get; set; } + public string Message { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/INeatSavesService.cs b/NeatShift/NeatShift/Services/INeatSavesService.cs new file mode 100644 index 0000000..18d61ff --- /dev/null +++ b/NeatShift/NeatShift/Services/INeatSavesService.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using NeatShift.Models; + +namespace NeatShift.Services +{ + public interface INeatSavesService + { + Task CreateNeatSave(string sourcePath, string destinationPath, string description); + List GetNeatSaves(); + Task<(bool success, string operationId)> RestoreNeatSave(string operationId); + Task DeleteNeatSave(string operationId); + Task Initialize(); + bool IsInitialized { get; } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/IOHelper.cs b/NeatShift/NeatShift/Services/IOHelper.cs new file mode 100644 index 0000000..89967a5 --- /dev/null +++ b/NeatShift/NeatShift/Services/IOHelper.cs @@ -0,0 +1,317 @@ +using System; +using System.IO; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Collections.Generic; +using System.Linq; +using System.Diagnostics; + +namespace NeatShift.Services +{ + [SupportedOSPlatform("windows")] + public static class IOHelper + { + [SupportedOSPlatform("windows")] + public static bool HasWritePermission(string path) + { + try + { + var directoryInfo = new DirectoryInfo(path); + var security = directoryInfo.GetAccessControl(); + var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); + + var currentUser = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(currentUser); + + foreach (FileSystemAccessRule rule in rules) + { + if (currentUser.User?.Equals(rule.IdentityReference) == true || + principal.IsInRole((SecurityIdentifier)rule.IdentityReference)) + { + if ((rule.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write) + { + if (rule.AccessControlType == AccessControlType.Allow) + return true; + } + } + } + return false; + } + catch + { + return false; + } + } + + [SupportedOSPlatform("windows")] + public static bool CreateSymbolicLink(string linkPath, string targetPath, bool isDirectory, bool hideLink = true) + { + try + { + bool success = NativeMethods.CreateSymbolicLink( + linkPath, + targetPath, + isDirectory ? NativeMethods.SymbolicLink.Directory : NativeMethods.SymbolicLink.File); + + if (success && hideLink) + { + HideSymbolicLink(linkPath); + } + + return success; + } + catch + { + return false; + } + } + + public static bool HideSymbolicLink(string path) + { + try + { + var attributes = File.GetAttributes(path); + // Add Hidden and System attributes while preserving existing attributes + attributes |= FileAttributes.Hidden | FileAttributes.System; + File.SetAttributes(path, attributes); + return true; + } + catch + { + return false; + } + } + + public static bool ShowSymbolicLink(string path) + { + try + { + var attributes = File.GetAttributes(path); + // Remove Hidden and System attributes while preserving others + attributes &= ~(FileAttributes.Hidden | FileAttributes.System); + File.SetAttributes(path, attributes); + return true; + } + catch + { + return false; + } + } + + public static bool IsSymbolicLink(string path) + { + try + { + var attributes = File.GetAttributes(path); + return attributes.HasFlag(FileAttributes.ReparsePoint); + } + catch + { + return false; + } + } + + public static string GetSymbolicLinkTarget(string path) + { + try + { + if (!IsSymbolicLink(path)) + return string.Empty; + + var targetPath = Path.GetFullPath(path); + if (Directory.Exists(targetPath)) + { + var info = new DirectoryInfo(targetPath); + return Path.GetFullPath(info.LinkTarget ?? string.Empty); + } + else if (File.Exists(targetPath)) + { + var info = new FileInfo(targetPath); + return Path.GetFullPath(info.LinkTarget ?? string.Empty); + } + + return string.Empty; + } + catch + { + return string.Empty; + } + } + + public static IEnumerable<(string Path, string Target, bool IsHidden)> GetSymbolicLinks(string directoryPath) + { + try + { + var directory = new DirectoryInfo(directoryPath); + var results = new List<(string, string, bool)>(); + + // Get all files and directories, including hidden ones + var items = directory.GetFileSystemInfos("*", SearchOption.TopDirectoryOnly); + + foreach (var item in items) + { + if (item.Attributes.HasFlag(FileAttributes.ReparsePoint)) + { + bool isHidden = item.Attributes.HasFlag(FileAttributes.Hidden); + string target = string.Empty; + + if (item is DirectoryInfo dirInfo) + { + target = dirInfo.LinkTarget ?? string.Empty; + } + else if (item is FileInfo fileInfo) + { + target = fileInfo.LinkTarget ?? string.Empty; + } + + results.Add((item.FullName, target, isHidden)); + } + } + + return results; + } + catch (Exception ex) + { + Debug.WriteLine($"Error getting symbolic links: {ex.Message}"); + return Enumerable.Empty<(string, string, bool)>(); + } + } + + public static IEnumerable<(string Path, string Target, bool IsHidden)> GetAllSymbolicLinks(string directoryPath) + { + try + { + var directory = new DirectoryInfo(directoryPath); + var results = new List<(string, string, bool)>(); + + // Get all files and directories recursively, including hidden ones + var items = directory.GetFileSystemInfos("*", SearchOption.AllDirectories); + + foreach (var item in items) + { + if (item.Attributes.HasFlag(FileAttributes.ReparsePoint)) + { + bool isHidden = item.Attributes.HasFlag(FileAttributes.Hidden); + string target = string.Empty; + + if (item is DirectoryInfo dirInfo) + { + target = dirInfo.LinkTarget ?? string.Empty; + } + else if (item is FileInfo fileInfo) + { + target = fileInfo.LinkTarget ?? string.Empty; + } + + results.Add((item.FullName, target, isHidden)); + } + } + + return results; + } + catch (Exception ex) + { + Debug.WriteLine($"Error getting symbolic links: {ex.Message}"); + return Enumerable.Empty<(string, string, bool)>(); + } + } + + public static bool ToggleSymbolicLinkVisibility(string path) + { + try + { + var attributes = File.GetAttributes(path); + if (attributes.HasFlag(FileAttributes.Hidden)) + { + // Show the link + attributes &= ~(FileAttributes.Hidden | FileAttributes.System); + } + else + { + // Hide the link + attributes |= FileAttributes.Hidden | FileAttributes.System; + } + File.SetAttributes(path, attributes); + return true; + } + catch (Exception ex) + { + Debug.WriteLine($"Error toggling symbolic link visibility: {ex.Message}"); + return false; + } + } + + [SupportedOSPlatform("windows")] + public static bool DeleteSymbolicLink(string path) + { + try + { + if (!IsSymbolicLink(path)) + return false; + + // Remove read-only attribute if present + var attributes = File.GetAttributes(path); + if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly); + } + + // For directories, use Directory.Delete + if (Directory.Exists(path)) + { + Directory.Delete(path); + return true; + } + + // For files, use File.Delete + if (File.Exists(path)) + { + File.Delete(path); + return true; + } + + return false; + } + catch (Exception ex) + { + Debug.WriteLine($"Error deleting symbolic link: {ex.Message}"); + return false; + } + } + + private static void RemoveDirectoryWithRetry(string path, int retries = 3) + { + for (int i = 0; i < retries; i++) + { + try + { + Directory.Delete(path); + return; + } + catch (IOException) when (i < retries - 1) + { + System.Threading.Thread.Sleep(100); // Wait briefly before retry + } + } + throw new IOException($"Failed to delete directory after {retries} attempts"); + } + + private static void RemoveFileWithRetry(string path, int retries = 3) + { + for (int i = 0; i < retries; i++) + { + try + { + File.Delete(path); + return; + } + catch (IOException) when (i < retries - 1) + { + System.Threading.Thread.Sleep(100); // Wait briefly before retry + } + } + throw new IOException($"Failed to delete file after {retries} attempts"); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/IOOperation.cs b/NeatShift/NeatShift/Services/IOOperation.cs new file mode 100644 index 0000000..df026f7 --- /dev/null +++ b/NeatShift/NeatShift/Services/IOOperation.cs @@ -0,0 +1,77 @@ +using System; +using System.Threading; + +namespace NeatShift.Services +{ + public class IOOperation + { + private readonly CancellationTokenSource _cancellationTokenSource; + private bool _isCompleted; + private bool _isCancelled; + + public event EventHandler? ProgressChanged; + public event EventHandler? Completed; + public event EventHandler? Cancelled; + + public bool IsCompleted + { + get => _isCompleted; + private set + { + _isCompleted = value; + if (value) + { + OnCompleted(); + } + } + } + + public bool IsCancelled + { + get => _isCancelled; + private set + { + _isCancelled = value; + if (value) + { + OnCancelled(); + } + } + } + + public IOOperation() + { + _cancellationTokenSource = new CancellationTokenSource(); + } + + protected virtual void OnProgressChanged(int progressPercentage, string message) + { + ProgressChanged?.Invoke(this, new ProgressChangedEventArgs + { + ProgressPercentage = progressPercentage, + Message = message + }); + } + + protected virtual void OnCompleted() + { + Completed?.Invoke(this, EventArgs.Empty); + } + + protected virtual void OnCancelled() + { + Cancelled?.Invoke(this, EventArgs.Empty); + } + + public void Cancel() + { + _cancellationTokenSource.Cancel(); + IsCancelled = true; + } + + public CancellationToken GetCancellationToken() + { + return _cancellationTokenSource.Token; + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/ISettingsService.cs b/NeatShift/NeatShift/Services/ISettingsService.cs new file mode 100644 index 0000000..114c084 --- /dev/null +++ b/NeatShift/NeatShift/Services/ISettingsService.cs @@ -0,0 +1,22 @@ +using NeatShift.Models; + +namespace NeatShift.Services +{ + public interface ISettingsService + { + Settings LoadSettings(); + void SaveSettings(Settings settings); + bool GetCreateRestorePoint(); + void SetCreateRestorePoint(bool value); + bool GetHideSymbolicLinks(); + void SetHideSymbolicLinks(bool value); + + // NeatSaves settings + bool GetUseNeatSaves(); + void SetUseNeatSaves(bool value); + int GetMaxNeatSaves(); + void SetMaxNeatSaves(int value); + string GetNeatSavesLocation(); + void SetNeatSavesLocation(string path); + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/ISystemRestoreService.cs b/NeatShift/NeatShift/Services/ISystemRestoreService.cs new file mode 100644 index 0000000..8bc09b5 --- /dev/null +++ b/NeatShift/NeatShift/Services/ISystemRestoreService.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using NeatShift.Models; + +namespace NeatShift.Services +{ + public interface ISystemRestoreService + { + Task CreateRestorePoint(string description); + Task> GetRestorePoints(); + Task DeleteRestorePoint(string sequenceNumber); + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/NativeMethods.cs b/NeatShift/NeatShift/Services/NativeMethods.cs new file mode 100644 index 0000000..1237a68 --- /dev/null +++ b/NeatShift/NeatShift/Services/NativeMethods.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.InteropServices; + +namespace NeatShift.Services +{ + internal static class NativeMethods + { + public const int BEGIN_SYSTEM_CHANGE = 100; + public const int MODIFY_SETTINGS = 12; + + [StructLayout(LayoutKind.Sequential)] + public struct RESTORE_POINT + { + public int dwEventType; + public int dwRestorePtType; + public Int64 llSequenceNumber; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] + public string szDescription; + } + + [DllImport("srrestorept.dll", EntryPoint = "SRSetRestorePointW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] + public static extern int SRSetRestorePoint(RESTORE_POINT? restorePoint, out int status); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, SymbolicLink dwFlags); + + public enum SymbolicLink + { + File = 0, + Directory = 1 + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/NeatSavesService.cs b/NeatShift/NeatShift/Services/NeatSavesService.cs new file mode 100644 index 0000000..1676875 --- /dev/null +++ b/NeatShift/NeatShift/Services/NeatSavesService.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using System.Threading.Tasks; +using System.Linq; +using System.Diagnostics; +using NeatShift.Models; + +namespace NeatShift.Services +{ + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public class NeatSavesService : INeatSavesService + { + private readonly string _operationsFile; + private readonly NeatSavesSettings _settings; + private List _operations; + private bool _isInitialized; + + public bool IsInitialized => _isInitialized; + + public NeatSavesService(NeatSavesSettings settings) + { + _settings = settings; + _operations = new List(); + _operationsFile = Path.Combine(_settings.SaveLocation, "operations.json"); + } + + public async Task Initialize() + { + try + { + if (!Directory.Exists(_settings.SaveLocation)) + { + Directory.CreateDirectory(_settings.SaveLocation); + } + + if (File.Exists(_operationsFile)) + { + string json = await File.ReadAllTextAsync(_operationsFile); + _operations = JsonSerializer.Deserialize>(json) ?? new List(); + } + + _isInitialized = true; + return true; + } + catch (Exception ex) + { + Debug.WriteLine($"Error initializing NeatSaves: {ex.Message}"); + return false; + } + } + + public async Task CreateNeatSave(string sourcePath, string destinationPath, string description) + { + if (!_isInitialized) return false; + + try + { + var operation = new NeatSavesOperation + { + Description = description, + SourcePath = sourcePath, + DestinationPath = destinationPath, + CreationTime = DateTime.Now + }; + + // Add to operations list + _operations.Add(operation); + + // Maintain max operations limit + while (_operations.Count > _settings.MaxOperationsToKeep) + { + var oldestOp = _operations.OrderBy(o => o.CreationTime).First(); + await DeleteNeatSave(oldestOp.Id); + } + + // Save operations list + await SaveOperations(); + return true; + } + catch (Exception ex) + { + Debug.WriteLine($"Error creating NeatSave: {ex.Message}"); + return false; + } + } + + public List GetNeatSaves() + { + return _operations.OrderByDescending(o => o.CreationTime).ToList(); + } + + public async Task<(bool success, string operationId)> RestoreNeatSave(string operationId) + { + if (!_isInitialized) return (false, string.Empty); + + try + { + var operation = _operations.FirstOrDefault(o => o.Id == operationId); + if (operation == null) return (false, string.Empty); + + // Split the source paths (they were joined with semicolons during save) + var sourcePaths = operation.SourcePath.Split(';', StringSplitOptions.RemoveEmptyEntries); + + foreach (var sourcePath in sourcePaths) + { + // Get the corresponding destination path + string fileName = Path.GetFileName(sourcePath); + string destinationPath = Path.Combine(operation.DestinationPath, fileName); + + // Verify destination exists + if (!File.Exists(destinationPath) && !Directory.Exists(destinationPath)) + { + throw new FileNotFoundException($"The moved file no longer exists at destination: {destinationPath}"); + } + + // Delete symbolic link at source if it exists + if (File.Exists(sourcePath)) + { + var attributes = File.GetAttributes(sourcePath); + if ((attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) + { + File.Delete(sourcePath); + } + } + else if (Directory.Exists(sourcePath)) + { + var attributes = File.GetAttributes(sourcePath); + if ((attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint) + { + Directory.Delete(sourcePath); + } + } + + // Move file back to original location + if (File.Exists(destinationPath)) + { + File.Move(destinationPath, sourcePath, true); + } + else if (Directory.Exists(destinationPath)) + { + if (Directory.Exists(sourcePath)) + { + Directory.Delete(sourcePath, true); // Remove existing directory if any + } + Directory.Move(destinationPath, sourcePath); + } + } + + return (true, operationId); // Return both success and operationId + } + catch (Exception ex) + { + Debug.WriteLine($"Error restoring NeatSave: {ex.Message}"); + return (false, string.Empty); + } + } + + public async Task DeleteNeatSave(string operationId) + { + if (!_isInitialized) return false; + + try + { + var operation = _operations.FirstOrDefault(o => o.Id == operationId); + if (operation == null) return false; + + _operations.Remove(operation); + await SaveOperations(); + return true; + } + catch (Exception ex) + { + Debug.WriteLine($"Error deleting NeatSave: {ex.Message}"); + return false; + } + } + + private async Task SaveOperations() + { + string json = JsonSerializer.Serialize(_operations); + await File.WriteAllTextAsync(_operationsFile, json); + } + + private void CopyDirectory(string sourceDir, string destinationDir) + { + // Create the destination directory + Directory.CreateDirectory(destinationDir); + + // Copy all files + foreach (string filePath in Directory.GetFiles(sourceDir)) + { + string fileName = Path.GetFileName(filePath); + string destFile = Path.Combine(destinationDir, fileName); + File.Copy(filePath, destFile); + } + + // Copy all subdirectories + foreach (string dirPath in Directory.GetDirectories(sourceDir)) + { + string dirName = Path.GetFileName(dirPath); + string destDir = Path.Combine(destinationDir, dirName); + CopyDirectory(dirPath, destDir); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/RecentLocationsService.cs b/NeatShift/NeatShift/Services/RecentLocationsService.cs new file mode 100644 index 0000000..8b6adf5 --- /dev/null +++ b/NeatShift/NeatShift/Services/RecentLocationsService.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace NeatShift.Services +{ + public interface IRecentLocationsService + { + List LoadRecentLocations(); + void SaveRecentLocations(IEnumerable locations); + } + + public class RecentLocationsService : IRecentLocationsService + { + private readonly string _filePath; + + public RecentLocationsService() + { + var appDataPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "NeatShift" + ); + + // Create directory if it doesn't exist + if (!Directory.Exists(appDataPath)) + { + Directory.CreateDirectory(appDataPath); + } + + _filePath = Path.Combine(appDataPath, "recent_locations.json"); + } + + public List LoadRecentLocations() + { + try + { + if (File.Exists(_filePath)) + { + var json = File.ReadAllText(_filePath); + var locations = JsonSerializer.Deserialize>(json); + return locations ?? new List(); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Error loading recent locations: {ex.Message}"); + } + + return new List(); + } + + public void SaveRecentLocations(IEnumerable locations) + { + try + { + var json = JsonSerializer.Serialize(locations); + File.WriteAllText(_filePath, json); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Error saving recent locations: {ex.Message}"); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/SettingsService.cs b/NeatShift/NeatShift/Services/SettingsService.cs new file mode 100644 index 0000000..6684cb9 --- /dev/null +++ b/NeatShift/NeatShift/Services/SettingsService.cs @@ -0,0 +1,143 @@ +using System; +using System.IO; +using System.Text.Json; +using NeatShift.Models; + +namespace NeatShift.Services +{ + public class SettingsService : ISettingsService + { + private readonly string _settingsPath; + private Models.Settings _currentSettings; + private readonly ISystemRestoreService _systemRestoreService; + + public SettingsService(ISystemRestoreService systemRestoreService) + { + _systemRestoreService = systemRestoreService ?? throw new ArgumentNullException(nameof(systemRestoreService)); + _settingsPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "NeatShift", + "settings.json"); + + _currentSettings = LoadSettings(); + } + + public Models.Settings LoadSettings() + { + if (!File.Exists(_settingsPath)) + { + _currentSettings = new Models.Settings(); + SaveSettings(_currentSettings); + return _currentSettings; + } + + try + { + string json = File.ReadAllText(_settingsPath); + var options = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }; + var settings = JsonSerializer.Deserialize(json, options); + _currentSettings = settings ?? new Models.Settings(); + return _currentSettings; + } + catch + { + _currentSettings = new Models.Settings(); + SaveSettings(_currentSettings); + return _currentSettings; + } + } + + public void SaveSettings(Models.Settings settings) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + string directory = Path.GetDirectoryName(_settingsPath) ?? + throw new InvalidOperationException("Invalid settings path"); + + Directory.CreateDirectory(directory); + + var options = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNameCaseInsensitive = true + }; + string json = JsonSerializer.Serialize(settings, options); + File.WriteAllText(_settingsPath, json); + _currentSettings = settings; + } + + public bool GetCreateRestorePoint() + { + return _currentSettings.CreateRestorePoint; + } + + public void SetCreateRestorePoint(bool value) + { + if (_currentSettings.CreateRestorePoint != value) + { + _currentSettings.CreateRestorePoint = value; + SaveSettings(_currentSettings); + } + } + + public bool GetHideSymbolicLinks() + { + return _currentSettings.HideSymbolicLinks; + } + + public void SetHideSymbolicLinks(bool value) + { + if (_currentSettings.HideSymbolicLinks != value) + { + _currentSettings.HideSymbolicLinks = value; + SaveSettings(_currentSettings); + } + } + + // NeatSaves settings implementation + public bool GetUseNeatSaves() + { + return _currentSettings.UseNeatSaves; + } + + public void SetUseNeatSaves(bool value) + { + if (_currentSettings.UseNeatSaves != value) + { + _currentSettings.UseNeatSaves = value; + SaveSettings(_currentSettings); + } + } + + public int GetMaxNeatSaves() + { + return _currentSettings.MaxNeatSaves; + } + + public void SetMaxNeatSaves(int value) + { + if (_currentSettings.MaxNeatSaves != value) + { + _currentSettings.MaxNeatSaves = value; + SaveSettings(_currentSettings); + } + } + + public string GetNeatSavesLocation() + { + return _currentSettings.NeatSavesLocation; + } + + public void SetNeatSavesLocation(string path) + { + if (_currentSettings.NeatSavesLocation != path) + { + _currentSettings.NeatSavesLocation = path; + SaveSettings(_currentSettings); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/SystemRestoreService.cs b/NeatShift/NeatShift/Services/SystemRestoreService.cs new file mode 100644 index 0000000..5f7eec3 --- /dev/null +++ b/NeatShift/NeatShift/Services/SystemRestoreService.cs @@ -0,0 +1,427 @@ +// NeatShift - Easily move files while keeping them accessible +// Copyright (C) 2024 BytexGrid +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Diagnostics; +using NeatShift.Models; +using System.Linq; +using System.Runtime.InteropServices; + +namespace NeatShift.Services +{ + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + public class SystemRestoreService : ISystemRestoreService + { + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern IntPtr LoadLibrary(string lpFileName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)] + private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); + + private bool? _isSystemRestoreAvailable; + + public SystemRestoreService() + { + Debug.WriteLine("Initializing SystemRestoreService..."); + } + + private async Task IsSystemRestoreAvailable() + { + if (_isSystemRestoreAvailable.HasValue) + return _isSystemRestoreAvailable.Value; + + try + { + // Just try to launch the System Protection dialog to check if it's available + using var process = Process.Start(new ProcessStartInfo + { + FileName = "SystemPropertiesProtection.exe", + UseShellExecute = true, + Verb = "runas", + WindowStyle = ProcessWindowStyle.Hidden, + CreateNoWindow = true + }); + + if (process != null) + { + await Task.Delay(500); // Give it a moment to start + process.Kill(); // Close it immediately + _isSystemRestoreAvailable = true; + } + else + { + _isSystemRestoreAvailable = false; + } + } + catch (Exception ex) + { + Debug.WriteLine($"Error checking system restore availability: {ex.Message}"); + _isSystemRestoreAvailable = false; + } + + return _isSystemRestoreAvailable.Value; + } + + public async Task> GetRestorePoints() + { + var restorePoints = new List(); + + try + { + // Use PowerShell to get restore points + using var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + Arguments = @"-NoProfile -Command ""& { + Get-ComputerRestorePoint | ForEach-Object { + $seq = $_.SequenceNumber + $timeStr = $_.CreationTime + $desc = $_.Description + Write-Output ($seq.ToString() + '|' + $timeStr + '|' + $desc) + } + }""", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + } + }; + + process.Start(); + string output = await process.StandardOutput.ReadToEndAsync(); + string error = await process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + Debug.WriteLine($"PowerShell output: {output}"); + if (!string.IsNullOrEmpty(error)) + { + Debug.WriteLine($"PowerShell error: {error}"); + } + + // Parse the output line by line + var lines = output.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + foreach (var line in lines) + { + var parts = line.Split('|'); + if (parts.Length == 3) + { + if (int.TryParse(parts[0], out int sequenceNumber)) + { + // Parse the special format: yyyyMMddHHmmss.ffffff-000 + var timeStr = parts[1].Trim(); + if (timeStr.Length >= 14) // At least yyyyMMddHHmmss + { + try + { + var creationTime = ParseRestorePointTime(timeStr); + + restorePoints.Add(new RestorePoint + { + Id = sequenceNumber.ToString(), + Description = parts[2].Trim(), + CreationTime = creationTime + }); + } + catch (Exception ex) + { + Debug.WriteLine($"Error parsing time {timeStr}: {ex.Message}"); + } + } + } + } + } + } + catch (Exception ex) + { + Debug.WriteLine($"Error getting restore points: {ex.Message}"); + Debug.WriteLine($"Stack trace: {ex.StackTrace}"); + } + + // Sort by creation time (newest first) + return restorePoints.OrderByDescending(p => p.CreationTime).ToList(); + } + + public async Task CreateRestorePoint(string description) + { + if (!await IsSystemRestoreAvailable()) + { + Debug.WriteLine("System restore is not available"); + return false; + } + + try + { + // Get current restore points to compare after creation + var beforePoints = await GetRestorePoints(); + var beforeCount = beforePoints.Count; + var lastSequence = beforePoints.Any() ? int.Parse(beforePoints.First().Id) : 0; + + Debug.WriteLine($"Before creation - Points: {beforeCount}, Last sequence: {lastSequence}"); + + // Create restore point using PowerShell + using var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + Arguments = $@"-Command ""& {{ + Enable-ComputerRestore -Drive 'C:\'; + Checkpoint-Computer -Description '{description}' -RestorePointType 'MODIFY_SETTINGS' + }}""", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + Verb = "runas", + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + } + }; + + process.Start(); + string output = await process.StandardOutput.ReadToEndAsync(); + string error = await process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + Debug.WriteLine($"Create restore point results:"); + Debug.WriteLine($"- Output: {output}"); + Debug.WriteLine($"- Error: {error}"); + Debug.WriteLine($"- Exit code: {process.ExitCode}"); + + // Check for 3-minute warning in both output and error + if (output.Contains("cannot be created because one has already been created within the past 3 minutes") || + error.Contains("cannot be created because one has already been created within the past 3 minutes") || + output.Contains("WARNING: A new system restore point cannot be created") || + error.Contains("WARNING: A new system restore point cannot be created")) + { + Debug.WriteLine("3-minute cooldown warning detected"); + return false; + } + + // Wait a moment for the restore point to be registered + await Task.Delay(1000); + + // Verify the restore point was created + var afterPoints = await GetRestorePoints(); + var afterCount = afterPoints.Count; + var newSequence = afterPoints.Any() ? int.Parse(afterPoints.First().Id) : 0; + + Debug.WriteLine($"After creation - Points: {afterCount}, New sequence: {newSequence}"); + + bool success = process.ExitCode == 0 && + afterCount > beforeCount && + newSequence > lastSequence; + + Debug.WriteLine($"Creation verification:"); + Debug.WriteLine($"- Exit code success: {process.ExitCode == 0}"); + Debug.WriteLine($"- Count increased: {afterCount > beforeCount}"); + Debug.WriteLine($"- New sequence: {newSequence > lastSequence}"); + Debug.WriteLine($"- Overall success: {success}"); + + return success; + } + catch (Exception ex) + { + Debug.WriteLine($"Error creating restore point: {ex.Message}"); + Debug.WriteLine($"Stack trace: {ex.StackTrace}"); + return false; + } + } + + private DateTime ParseRestorePointTime(string timeStr) + { + try + { + // Format: yyyyMMddHHmmss.ffffff-000 + var year = int.Parse(timeStr.Substring(0, 4)); + var month = int.Parse(timeStr.Substring(4, 2)); + var day = int.Parse(timeStr.Substring(6, 2)); + var hour = int.Parse(timeStr.Substring(8, 2)); + var minute = int.Parse(timeStr.Substring(10, 2)); + var second = int.Parse(timeStr.Substring(12, 2)); + + // Convert to local time since PowerShell returns UTC + var utcTime = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Utc); + return utcTime.ToLocalTime(); + } + catch (Exception ex) + { + Debug.WriteLine($"Error parsing time {timeStr}: {ex.Message}"); + return DateTime.Now; // Fallback to current time + } + } + + public async Task DeleteRestorePoint(string sequenceNumber) + { + try + { + // First try using srdeletepoint.exe (Windows built-in tool) + using (var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "powershell.exe", + Arguments = $"-NoProfile -Command \"& {{ srdeletepoint.exe /n {sequenceNumber} }}\"", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + Verb = "runas", + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + } + }) + { + process.Start(); + string output = await process.StandardOutput.ReadToEndAsync(); + string error = await process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + Debug.WriteLine($"srdeletepoint results:"); + Debug.WriteLine($"- Output: {output}"); + Debug.WriteLine($"- Error: {error}"); + Debug.WriteLine($"- Exit code: {process.ExitCode}"); + + // Check if the point still exists + var points = await GetRestorePoints(); + bool pointStillExists = points.Any(p => p.Id == sequenceNumber); + + if (!pointStillExists) + { + Debug.WriteLine("Restore point deleted successfully via srdeletepoint"); + return true; + } + } + + // If srdeletepoint failed, try using vssadmin to delete the shadow copy + Debug.WriteLine("srdeletepoint failed, trying vssadmin..."); + + // Get the restore point's creation time + var allPoints = await GetRestorePoints(); + var targetPoint = allPoints.FirstOrDefault(p => p.Id == sequenceNumber); + if (targetPoint == null) + { + Debug.WriteLine("Could not find target restore point"); + return false; + } + + // Get shadow copies and find the matching one + using (var listProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "cmd.exe", + Arguments = "/c vssadmin list shadows", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + } + }) + { + listProcess.Start(); + string listOutput = await listProcess.StandardOutput.ReadToEndAsync(); + await listProcess.WaitForExitAsync(); + + Debug.WriteLine($"VSS list output: {listOutput}"); + + // Find the shadow copy ID for our restore point's time + string? shadowId = null; + DateTime? shadowTime = null; + var lines = listOutput.Split('\n'); + + for (int i = 0; i < lines.Length; i++) + { + var line = lines[i].Trim(); + if (line.Contains("creation time:")) + { + var timeStr = line.Substring(line.IndexOf(':') + 1).Trim(); + if (DateTime.TryParse(timeStr, out DateTime time)) + { + // Look ahead for Shadow Copy ID + for (int j = i + 1; j < Math.Min(i + 5, lines.Length); j++) + { + var idLine = lines[j].Trim(); + if (idLine.StartsWith("Shadow Copy ID:")) + { + var id = idLine.Substring(idLine.IndexOf('{')); + // If this time is closer to our target time than the previous match + if (shadowTime == null || + Math.Abs((time - targetPoint.CreationTime).TotalMinutes) < + Math.Abs((shadowTime.Value - targetPoint.CreationTime).TotalMinutes)) + { + shadowId = id; + shadowTime = time; + Debug.WriteLine($"Found potential match: ID={id}, Time={time}"); + } + break; + } + } + } + } + } + + if (shadowId != null && shadowTime != null) + { + Debug.WriteLine($"Using shadow ID: {shadowId} (created at {shadowTime})"); + Debug.WriteLine($"Target point time: {targetPoint.CreationTime}"); + Debug.WriteLine($"Time difference: {Math.Abs((shadowTime.Value - targetPoint.CreationTime).TotalMinutes)} minutes"); + + // Try to delete the shadow copy + using var deleteProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "cmd.exe", + Arguments = $"/c vssadmin delete shadows /Shadow={shadowId} /Quiet", + UseShellExecute = true, + Verb = "runas", + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden + } + }; + + deleteProcess.Start(); + await deleteProcess.WaitForExitAsync(); + + // Final check if the restore point was deleted + var finalPoints = await GetRestorePoints(); + bool stillExists = finalPoints.Any(p => p.Id == sequenceNumber); + Debug.WriteLine($"After vssadmin delete - Point still exists: {stillExists}"); + + return !stillExists; + } + else + { + Debug.WriteLine("Could not find matching shadow copy"); + } + } + + return false; + } + catch (Exception ex) + { + Debug.WriteLine($"Error deleting restore point: {ex.Message}"); + Debug.WriteLine($"Stack trace: {ex.StackTrace}"); + return false; + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Services/UpdateService.cs b/NeatShift/NeatShift/Services/UpdateService.cs new file mode 100644 index 0000000..b042e5b --- /dev/null +++ b/NeatShift/NeatShift/Services/UpdateService.cs @@ -0,0 +1,44 @@ +using System; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; + +namespace NeatShift.Services +{ + public class UpdateService + { + private readonly HttpClient _httpClient; + private const string GITHUB_API_URL = "https://api.github.com/repos/BytexGrid/NeatShift/releases/latest"; + + public UpdateService() + { + _httpClient = new HttpClient(); + _httpClient.DefaultRequestHeaders.Add("User-Agent", "NeatShift"); + } + + public async Task<(bool IsUpdateAvailable, string LatestVersion)> CheckForUpdates() + { + try + { + var response = await _httpClient.GetStringAsync(GITHUB_API_URL); + using var document = JsonDocument.Parse(response); + var root = document.RootElement; + var latestVersion = root.GetProperty("tag_name").GetString()?.TrimStart('v'); + + if (string.IsNullOrEmpty(latestVersion)) + return (false, NeatShift.Version.Current); + + // Compare versions using System.Version + var current = new System.Version(NeatShift.Version.Current); + var latest = new System.Version(latestVersion); + + return (latest > current, latestVersion); + } + catch + { + // Fail silently - don't bother user if update check fails + return (false, NeatShift.Version.Current); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Version.cs b/NeatShift/NeatShift/Version.cs new file mode 100644 index 0000000..3828006 --- /dev/null +++ b/NeatShift/NeatShift/Version.cs @@ -0,0 +1,17 @@ +namespace NeatShift +{ + public static class Version + { + public static string Current + { + get + { + var assembly = System.Reflection.Assembly.GetExecutingAssembly(); + var version = assembly.GetName().Version; + return version?.ToString() ?? "2.0.0"; + } + } + public const string Copyright = "© 2024 BytexGrid"; + public const string Description = "A modern file organization tool with symbolic link support."; + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/ViewModels/FileBrowserViewModel.cs b/NeatShift/NeatShift/ViewModels/FileBrowserViewModel.cs new file mode 100644 index 0000000..ba0a8f8 --- /dev/null +++ b/NeatShift/NeatShift/ViewModels/FileBrowserViewModel.cs @@ -0,0 +1,591 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Windows.Media.Imaging; +using System.Runtime.InteropServices; +using NeatShift.Services; + +namespace NeatShift.ViewModels +{ + public partial class FileBrowserViewModel : ObservableObject + { + private readonly Stack _backStack = new(); + private readonly Stack _forwardStack = new(); + private readonly ObservableCollection _recentLocations = new(); + private const int MAX_RECENT_LOCATIONS = 10; + private readonly IRecentLocationsService _recentLocationsService; + + [ObservableProperty] + private string _currentPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + + [ObservableProperty] + private ObservableCollection _items = new(); + + [ObservableProperty] + private FileItem? _selectedItem; + + [ObservableProperty] + private string _sortColumn = "Name"; + + [ObservableProperty] + private bool _sortAscending = true; + + [ObservableProperty] + private bool _isGridView = false; + + [ObservableProperty] + private bool _isEditingPath = false; + + [ObservableProperty] + private bool _isSelectionMode = false; + + [ObservableProperty] + private ObservableCollection _selectedItems = new(); + + private string _originalPath = string.Empty; + + [ObservableProperty] + private ObservableCollection _pathSegments = new(); + + public bool CanNavigateBack => _backStack.Any(); + public bool CanNavigateForward => _forwardStack.Any(); + + public ObservableCollection RecentLocations => _recentLocations; + + public FileBrowserViewModel(IRecentLocationsService recentLocationsService) + { + _recentLocationsService = recentLocationsService; + LoadItems(_currentPath); + UpdatePathSegments(); + SelectedItems.CollectionChanged += (s, e) => + { + System.Diagnostics.Debug.WriteLine($"Selected items count: {SelectedItems.Count}"); + }; + + // Load saved recent locations + var savedLocations = _recentLocationsService.LoadRecentLocations(); + foreach (var location in savedLocations.Take(MAX_RECENT_LOCATIONS)) + { + _recentLocations.Add(location); + } + } + + private void UpdatePathSegments() + { + PathSegments.Clear(); + var path = CurrentPath; + var segments = new List(); + + // Add drive root + var root = Path.GetPathRoot(path); + if (!string.IsNullOrEmpty(root)) + { + segments.Add(new PathSegment { Name = root, Path = root }); + path = path.Substring(root.Length); + + // Add each folder in path + var parts = path.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); + var currentPath = root; + foreach (var part in parts) + { + if (!string.IsNullOrEmpty(currentPath)) + { + currentPath = Path.Combine(currentPath, part); + segments.Add(new PathSegment { Name = part, Path = currentPath }); + } + } + + // Mark last segment + if (segments.Any()) + segments.Last().IsLast = true; + + foreach (var segment in segments) + PathSegments.Add(segment); + } + } + + [RelayCommand] + private void NavigateToSegment(string path) + { + if (Directory.Exists(path)) + { + _backStack.Push(CurrentPath); + LoadItems(path); + } + } + + [RelayCommand] + private void Sort(string column) + { + if (SortColumn == column) + { + SortAscending = !SortAscending; + } + else + { + SortColumn = column; + SortAscending = true; + } + + var sorted = Items.ToList(); + IOrderedEnumerable orderedItems; + + // Always sort folders first + if (SortAscending) + { + orderedItems = sorted.OrderByDescending(x => x.IsDirectory).ThenBy(GetSortSelector(column)); + } + else + { + orderedItems = sorted.OrderByDescending(x => x.IsDirectory).ThenByDescending(GetSortSelector(column)); + } + + Items.Clear(); + foreach (var item in orderedItems) + { + Items.Add(item); + } + } + + private Func GetSortSelector(string column) + { + return column switch + { + "Name" => x => x.Name ?? string.Empty, + "Type" => x => x.Type, + "Size" => x => GetSizeForSorting(x), + "DateModified" => x => DateTime.Parse(x.DateModified), + _ => x => x.Name ?? string.Empty + }; + } + + private long GetSizeForSorting(FileItem item) + { + if (item.IsDirectory) return -1; + if (string.IsNullOrEmpty(item.Size)) return 0; + + try + { + var parts = item.Size.Split(' '); + if (parts.Length != 2) return 0; + + var value = double.Parse(parts[0]); + var unit = parts[1].ToUpper(); + + return unit switch + { + "B" => (long)value, + "KB" => (long)(value * 1024), + "MB" => (long)(value * 1024 * 1024), + "GB" => (long)(value * 1024 * 1024 * 1024), + "TB" => (long)(value * 1024 * 1024 * 1024 * 1024), + _ => 0 + }; + } + catch + { + return 0; + } + } + + [RelayCommand] + private void NavigateBack() + { + if (!_backStack.Any()) return; + _forwardStack.Push(CurrentPath); + LoadItems(_backStack.Pop()); + } + + [RelayCommand] + private void NavigateForward() + { + if (!_forwardStack.Any()) return; + _backStack.Push(CurrentPath); + LoadItems(_forwardStack.Pop()); + } + + [RelayCommand] + private void NavigateUp() + { + var parent = Directory.GetParent(CurrentPath); + if (parent != null) + { + _backStack.Push(CurrentPath); + LoadItems(parent.FullName); + } + } + + [RelayCommand] + private void NavigateToPath() + { + try + { + string path = CurrentPath; + if (Directory.Exists(path)) + { + _backStack.Push(CurrentPath); + LoadItems(path); + } + else + { + System.Windows.MessageBox.Show($"Directory not found: {path}", "Error", + System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); + } + } + catch (Exception ex) + { + System.Windows.MessageBox.Show($"Error navigating to path: {ex.Message}", "Error", + System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); + } + } + + [RelayCommand] + private void ClearRecentLocations() + { + _recentLocations.Clear(); + } + + [RelayCommand] + private void ItemDoubleClick() + { + if (SelectedItem == null) return; + + try + { + if (SelectedItem.IsDirectory) + { + _backStack.Push(CurrentPath); + LoadItems(SelectedItem.Path!); + } + else + { + try + { + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo + { + FileName = SelectedItem.Path!, + UseShellExecute = true + }); + } + catch (Exception ex) + { + System.Windows.MessageBox.Show($"Error opening file: {ex.Message}", "Error", + System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); + } + } + } + catch (Exception ex) + { + System.Windows.MessageBox.Show($"Error accessing path: {ex.Message}", "Error", + System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); + } + } + + [RelayCommand] + private void ToggleView() + { + IsGridView = !IsGridView; + } + + [RelayCommand] + private void TogglePathEdit() + { + IsEditingPath = !IsEditingPath; + } + + [RelayCommand] + private void ToggleSelectionMode() + { + IsSelectionMode = !IsSelectionMode; + System.Diagnostics.Debug.WriteLine($"Selection mode: {IsSelectionMode}"); + if (!IsSelectionMode) + { + SelectedItems.Clear(); + } + OnPropertyChanged(nameof(IsSelectionMode)); + } + + public void SelectAll() + { + System.Diagnostics.Debug.WriteLine("Selecting all items..."); + SelectedItems.Clear(); + foreach (var item in Items) + { + SelectedItems.Add(item); + } + System.Diagnostics.Debug.WriteLine($"Selected {SelectedItems.Count} items"); + + // If we're selecting all items, automatically enable selection mode + if (SelectedItems.Count > 0 && !IsSelectionMode) + { + IsSelectionMode = true; + } + } + + public bool CanDragItems => IsSelectionMode || SelectedItem != null; + + public IEnumerable GetDragPaths() + { + if (IsSelectionMode && SelectedItems.Any()) + { + return SelectedItems.Select(item => item.Path!).Where(path => path != null); + } + else if (SelectedItem?.Path != null) + { + return new[] { SelectedItem.Path }; + } + return Array.Empty(); + } + + public void HandleKeyDown(string key, bool controlKey) + { + System.Diagnostics.Debug.WriteLine($"Key pressed: {key}, Control: {controlKey}"); + if (controlKey && key == "A") + { + SelectAll(); + } + } + + public void HandlePathKeyDown(string key) + { + if (key == "Return") // WPF uses "Return" for Enter key + { + if (Directory.Exists(CurrentPath)) + { + _backStack.Push(CurrentPath); + LoadItems(CurrentPath); + IsEditingPath = false; + } + else + { + System.Windows.MessageBox.Show($"Directory not found: {CurrentPath}", "Error", + System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); + } + } + else if (key == "Escape") + { + // Restore the original path and exit edit mode + CurrentPath = _originalPath; + IsEditingPath = false; + } + } + + private void LoadItems(string path) + { + try + { + Items.Clear(); + CurrentPath = path; // Set the current path + UpdatePathSegments(); // Update path segments + AddToRecentLocations(path); // Add to recent locations when navigating + + foreach (var directory in Directory.GetDirectories(path)) + { + var dirInfo = new DirectoryInfo(directory); + if ((dirInfo.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) + { + Items.Add(new FileItem + { + Name = Path.GetFileName(directory), + Icon = GetIcon(directory, true), + Path = directory, + IsDirectory = true, + Type = "File folder", + Size = "", + DateModified = dirInfo.LastWriteTime.ToString("g") + }); + } + } + + foreach (var file in Directory.GetFiles(path)) + { + var fileInfo = new FileInfo(file); + if ((fileInfo.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) + { + Items.Add(new FileItem + { + Name = Path.GetFileName(file), + Icon = GetIcon(file, false), + Path = file, + IsDirectory = false, + Type = GetFileType(file), + Size = FormatFileSize(fileInfo.Length), + DateModified = fileInfo.LastWriteTime.ToString("g") + }); + } + } + + CurrentPath = path; + UpdatePathSegments(); + OnPropertyChanged(nameof(CanNavigateBack)); + OnPropertyChanged(nameof(CanNavigateForward)); + } + catch (Exception ex) + { + System.Windows.MessageBox.Show($"Error accessing path: {ex.Message}", "Error", + System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); + } + } + + private static BitmapImage? GetIcon(string path, bool isFolder) + { + try + { + Icon? icon; + if (isFolder) + { + using var folderIcon = ExtractIconFromExe(Environment.SystemDirectory + "\\shell32.dll", 3); + icon = folderIcon; + } + else + { + icon = Icon.ExtractAssociatedIcon(path); + } + + if (icon == null) return null; + + using var bitmap = icon.ToBitmap(); + using var stream = new MemoryStream(); + bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); + stream.Position = 0; + + var image = new BitmapImage(); + image.BeginInit(); + image.StreamSource = stream; + image.CacheOption = BitmapCacheOption.OnLoad; + image.EndInit(); + image.Freeze(); // Important for performance + return image; + } + catch + { + return null; + } + } + + [DllImport("shell32.dll", CharSet = CharSet.Auto)] + private static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex); + + private static Icon? ExtractIconFromExe(string file, int index) + { + var hIcon = ExtractIcon(IntPtr.Zero, file, index); + if (hIcon == IntPtr.Zero) return null; + return Icon.FromHandle(hIcon); + } + + private string GetFileType(string filePath) + { + try + { + var extension = Path.GetExtension(filePath).ToLower(); + if (string.IsNullOrEmpty(extension)) + return "File"; + + // Get file type description from registry + var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension); + if (key != null) + { + var type = key.GetValue(null) as string; + if (!string.IsNullOrEmpty(type)) + { + var typeKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(type); + if (typeKey != null) + { + var desc = typeKey.GetValue(null) as string; + if (!string.IsNullOrEmpty(desc)) + return desc; + } + } + } + return extension.TrimStart('.').ToUpper() + " File"; + } + catch + { + return Path.GetExtension(filePath).ToUpper() + " File"; + } + } + + private string FormatFileSize(long bytes) + { + string[] sizes = { "B", "KB", "MB", "GB", "TB" }; + int order = 0; + double size = bytes; + while (size >= 1024 && order < sizes.Length - 1) + { + order++; + size /= 1024; + } + return $"{size:0.##} {sizes[order]}"; + } + + private void AddToRecentLocations(string path) + { + // Remove the path if it already exists + var existingIndex = _recentLocations.IndexOf(path); + if (existingIndex != -1) + { + _recentLocations.RemoveAt(existingIndex); + } + + // Add to the beginning + _recentLocations.Insert(0, path); + + // Remove oldest if we exceed the limit + while (_recentLocations.Count > MAX_RECENT_LOCATIONS) + { + _recentLocations.RemoveAt(_recentLocations.Count - 1); + } + + // Save to disk + _recentLocationsService.SaveRecentLocations(_recentLocations); + + // Force UI update + OnPropertyChanged(nameof(RecentLocations)); + } + + partial void OnIsEditingPathChanged(bool value) + { + if (value) + { + // Entering edit mode - backup the current path + _originalPath = CurrentPath; + } + } + + partial void OnIsSelectionModeChanged(bool value) + { + if (!value) + { + SelectedItems.Clear(); + } + } + + public void RefreshCurrentDirectory() + { + LoadItems(CurrentPath); + } + } + + public class FileItem + { + public string? Name { get; set; } + public BitmapImage? Icon { get; set; } + public string? Path { get; set; } + public bool IsDirectory { get; set; } + public string Type { get; set; } = string.Empty; + public string Size { get; set; } = string.Empty; + public string DateModified { get; set; } = string.Empty; + } + + public class PathSegment + { + public string Name { get; set; } = string.Empty; + public string Path { get; set; } = string.Empty; + public bool IsLast { get; set; } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/ViewModels/MainWindowViewModel.cs b/NeatShift/NeatShift/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..27db85d --- /dev/null +++ b/NeatShift/NeatShift/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,580 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Controls; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using ModernWpf.Controls; +using NeatShift.Models; +using NeatShift.Services; +using NeatShift.Views; +using System.Runtime.Versioning; +using MessageBox = System.Windows.MessageBox; +using Microsoft.WindowsAPICodePack.Dialogs; + +namespace NeatShift.ViewModels +{ + [SupportedOSPlatform("windows7.0")] + public partial class MainWindowViewModel : ObservableObject + { + private readonly IFileOperationService _fileOperationService; + private readonly ISettingsService _settingsService; + private readonly INeatSavesService _neatSavesService; + private readonly FileBrowserViewModel _fileBrowserViewModel; + private string _sourceDirectory = string.Empty; + + [ObservableProperty] + private bool _isOperationInProgress; + + [ObservableProperty] + private string _statusMessage = string.Empty; + + [ObservableProperty] + private int _progressValue; + + public ObservableCollection SourceItems { get; } + + [ObservableProperty] + private string _destinationPath = string.Empty; + + public bool CanMove => !IsOperationInProgress; + + [ObservableProperty] + private bool _isDarkTheme; + + private bool _isGuideSelected = true; + + public bool IsGuideSelected + { + get => _isGuideSelected; + set + { + SetProperty(ref _isGuideSelected, value); + OnPropertyChanged(nameof(IsExplorerSelected)); + } + } + + public bool IsExplorerSelected => !_isGuideSelected; + + [RelayCommand] + private void SwitchView(string view) + { + IsGuideSelected = view == "Guide"; + } + + public MainWindowViewModel(IFileOperationService fileOperationService, ISettingsService settingsService, INeatSavesService neatSavesService, FileBrowserViewModel fileBrowserViewModel) + { + _fileOperationService = fileOperationService ?? throw new ArgumentNullException(nameof(fileOperationService)); + _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + _neatSavesService = neatSavesService ?? throw new ArgumentNullException(nameof(neatSavesService)); + SourceItems = new ObservableCollection(); + + // Initialize NeatSavesService + Task.Run(async () => + { + await _neatSavesService.Initialize(); + }).ConfigureAwait(false); + + var settings = _settingsService.LoadSettings(); + DestinationPath = settings.LastUsedPath; + IsDarkTheme = ModernWpf.ThemeManager.Current.ActualApplicationTheme == ModernWpf.ApplicationTheme.Dark; + + _fileOperationService.ProgressChanged += (s, e) => + { + ProgressValue = e.ProgressPercentage; + StatusMessage = e.Message; + }; + + _fileBrowserViewModel = fileBrowserViewModel; + SourceItems.CollectionChanged += (s, e) => + { + if (e.NewItems?.Count > 0) + { + // Store the directory of the first added item as our source directory + var firstItem = e.NewItems[0] as string; + if (!string.IsNullOrEmpty(firstItem)) + { + _sourceDirectory = Path.GetDirectoryName(firstItem) ?? string.Empty; + } + } + }; + } + + [RelayCommand] + private void RemoveItem(FileSystemItem? item) + { + if (item != null) + { + SourceItems.Remove(item); + } + } + + [RelayCommand] + private async Task OpenSettings() + { + var dialog = new SettingsDialog(_settingsService); + await dialog.ShowAsync(); + } + + [RelayCommand] + private async Task ViewSymbolicLinks() + { + using var dialog = new FolderBrowserDialog + { + Description = "Select folder to check for symbolic links", + UseDescriptionForTitle = true, + ShowNewFolderButton = false + }; + + if (dialog.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(dialog.SelectedPath)) + { + var linksDialog = new SymbolicLinksDialog(dialog.SelectedPath); + await linksDialog.ShowAsync(); + } + } + + partial void OnIsOperationInProgressChanged(bool value) + { + AddFilesCommand.NotifyCanExecuteChanged(); + AddFolderCommand.NotifyCanExecuteChanged(); + MoveCommand.NotifyCanExecuteChanged(); + OnPropertyChanged(nameof(CanMove)); + } + + [RelayCommand(CanExecute = nameof(CanExecuteFileOperations))] + private void AddFiles() + { + var dialog = new Microsoft.Win32.OpenFileDialog + { + Multiselect = true, + Title = "Select files to move" + }; + + if (dialog.ShowDialog() == true) + { + foreach (string file in dialog.FileNames) + { + if (!string.IsNullOrEmpty(file)) + { + SourceItems.Add(new FileSystemItem(file)); + } + } + } + } + + [RelayCommand(CanExecute = nameof(CanExecuteFileOperations))] + private void AddFolder() + { + using var dialog = new CommonOpenFileDialog + { + Title = "Select folders to move", + IsFolderPicker = true, + Multiselect = true + }; + + if (dialog.ShowDialog() == CommonFileDialogResult.Ok) + { + foreach (string folder in dialog.FileNames) + { + if (!string.IsNullOrEmpty(folder)) + { + SourceItems.Add(new FileSystemItem(folder)); + } + } + } + } + + [RelayCommand] + private void BrowseDestination() + { + using var dialog = new FolderBrowserDialog + { + Description = "Select destination folder", + UseDescriptionForTitle = true, + ShowNewFolderButton = true + }; + + if (dialog.ShowDialog() == DialogResult.OK) + { + if (!string.IsNullOrEmpty(dialog.SelectedPath)) + { + DestinationPath = dialog.SelectedPath; + var settings = _settingsService.LoadSettings(); + settings.LastUsedPath = dialog.SelectedPath; + _settingsService.SaveSettings(settings); + } + } + } + + [RelayCommand(CanExecute = nameof(CanExecuteFileOperations))] + private async Task Move() + { + if (!SourceItems.Any()) + { + MessageBox.Show( + "The source files list is empty.\n\n" + + "You can add files by:\n" + + "• Dragging files from the in-app explorer\n" + + "• Using the 'Add Files' button\n" + + "• Using the 'Add Folder' button\n" + + "• Dragging files from Windows Explorer", + "No Files to Move", + MessageBoxButton.OK, + MessageBoxImage.Information + ); + return; + } + + if (string.IsNullOrEmpty(DestinationPath)) + { + MessageBox.Show("Please select a destination folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return; + } + + // Show safety choice dialog if it's the first time + var settings = _settingsService.LoadSettings(); + if (!settings.HasShownSafetyChoice) + { + var safetyDialog = new SafetyChoiceDialog(); + if (safetyDialog.ShowDialog() != true) + { + return; // User cancelled + } + + // Save user's choices + settings.UseNeatSaves = safetyDialog.ViewModel.UseNeatSavesOnly || safetyDialog.ViewModel.UseBoth; + settings.CreateRestorePoint = safetyDialog.ViewModel.UseSystemRestoreOnly || safetyDialog.ViewModel.UseBoth; + + if (safetyDialog.ViewModel.RememberChoice) + { + settings.HasShownSafetyChoice = true; + } + + // Always save settings regardless of remember choice + _settingsService.SaveSettings(settings); + } + + // Show confirmation dialog + var result = MessageBox.Show( + $"Are you sure you want to move {SourceItems.Count} item(s) to:\n{DestinationPath}?", + "Confirm Move", + MessageBoxButton.YesNo, + MessageBoxImage.Question); + + if (result != MessageBoxResult.Yes) + { + return; + } + + await MoveFiles(); + } + + private bool CanExecuteFileOperations() => !IsOperationInProgress; + + public void AddSourceItem(string path) + { + var item = new FileSystemItem(path); + if (!SourceItems.Any(x => x.Path == item.Path)) + { + SourceItems.Add(item); + } + } + + [RelayCommand] + private void OpenGitHub() + { + Process.Start(new ProcessStartInfo + { + FileName = "https://github.com/BytexGrid/NeatShift", + UseShellExecute = true + }); + } + + [RelayCommand] + private async Task ShowAbout() + { + var dialog = new ContentDialog + { + Title = "About NeatShift", + CloseButtonText = "Close", + DefaultButton = ContentDialogButton.Close, + Content = new StackPanel + { + Children = + { + new TextBlock + { + Text = $"NeatShift v{Version.Current}\n\n" + + "A modern file organization tool with symbolic link support.\n\n" + + "Features:\n" + + "• Move files and folders while keeping them accessible\n" + + "• Create and manage symbolic links\n" + + "• System restore point creation\n" + + "• Modern Windows 11 style interface\n\n" + + "⚠️ Important Notice:\n" + + "NeatShift is currently in testing phase. While we implement safety measures, please:\n" + + "• Create manual backups or system restore points\n" + + "• Verify symbolic links after moving files\n" + + "• Report any issues through Discord or Telegram\n\n" + + "The software is provided 'as is', without warranty of any kind.\n\n" + + "© 2024 NeatShift", + TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(0, 0, 0, 10) + }, + new System.Windows.Controls.Button + { + Content = "Check for Updates", + HorizontalAlignment = System.Windows.HorizontalAlignment.Center, + Command = new RelayCommand(async () => await CheckForUpdates()) + } + } + } + }; + + await dialog.ShowAsync(); + } + + private async Task CheckForUpdates() + { + var updateService = new UpdateService(); + var (isUpdateAvailable, latestVersion) = await updateService.CheckForUpdates(); + + if (isUpdateAvailable) + { + var result = MessageBox.Show( + $"A new version ({latestVersion}) is available. Would you like to download it?", + "Update Available", + MessageBoxButton.YesNo, + MessageBoxImage.Information); + + if (result == MessageBoxResult.Yes) + { + Process.Start(new ProcessStartInfo + { + FileName = "https://github.com/BytexGrid/NeatShift/releases/latest", + UseShellExecute = true + }); + } + } + else + { + MessageBox.Show( + "You are using the latest version.", + "No Updates Available", + MessageBoxButton.OK, + MessageBoxImage.Information); + } + } + + [RelayCommand] + private async Task ShowContactDialog() + { + var dialog = new ContactDialog(); + await dialog.ShowAsync(); + } + + [RelayCommand] + private async Task ShowFeatureRequest() + { + var dialog = new FeatureRequestDialog(); + await dialog.ShowAsync(); + } + + [RelayCommand] + private async Task ManageRestorePoints() + { + var dialog = new RestorePointDialog(); + await dialog.ShowAsync(); + } + + [RelayCommand] + private void ToggleTheme() + { + IsDarkTheme = !IsDarkTheme; + ModernWpf.ThemeManager.Current.ApplicationTheme = IsDarkTheme + ? ModernWpf.ApplicationTheme.Dark + : ModernWpf.ApplicationTheme.Light; + } + + [RelayCommand] + private void ShowSafetyChoice() + { + var safetyDialog = new SafetyChoiceDialog(); + if (safetyDialog.ShowDialog() == true) + { + var settings = _settingsService.LoadSettings(); + settings.UseNeatSaves = safetyDialog.ViewModel.UseNeatSavesOnly || safetyDialog.ViewModel.UseBoth; + settings.CreateRestorePoint = safetyDialog.ViewModel.UseSystemRestoreOnly || safetyDialog.ViewModel.UseBoth; + + if (safetyDialog.ViewModel.RememberChoice) + { + settings.HasShownSafetyChoice = true; + } + + _settingsService.SaveSettings(settings); + } + } + + partial void OnStatusMessageChanged(string value) + { + if (value == "Operation completed successfully") + { + // If we're in the source directory, refresh it + if (_fileBrowserViewModel.CurrentPath == _sourceDirectory) + { + _fileBrowserViewModel.RefreshCurrentDirectory(); + } + // Clear the source directory after operation completes + _sourceDirectory = string.Empty; + } + } + + [ObservableProperty] + private NeatSavesManagementViewModel? _neatSavesManagement; + + [ObservableProperty] + private bool _showNeatSavesManagement; + + private async Task MoveFiles() + { + IsOperationInProgress = true; + ProgressValue = 0; + StatusMessage = "Starting operation..."; + + try + { + if (string.IsNullOrEmpty(DestinationPath)) + { + MessageBox.Show("Please select a destination folder.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return; + } + + if (!SourceItems.Any()) + { + MessageBox.Show("Please add files or folders to move.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); + return; + } + + var settings = _settingsService.LoadSettings(); + bool success = true; + var movedItems = new List(); + + foreach (var item in SourceItems.ToList()) + { + string destinationPath = Path.Combine(DestinationPath, Path.GetFileName(item.Path)); + bool itemSuccess = await _fileOperationService.MoveWithSymbolicLink(item.Path, destinationPath); + if (itemSuccess) + { + movedItems.Add(item.Path); + } + else + { + success = false; + } + } + + if (success) + { + StatusMessage = "Operation completed successfully"; + ProgressValue = 100; + + // Create NeatSave if enabled and files were moved + if (settings.UseNeatSaves && movedItems.Any()) + { + var neatSaveId = Guid.NewGuid().ToString(); + var description = $"Files moved from {_sourceDirectory} to {DestinationPath}"; + try + { + bool neatSaveSuccess = await _neatSavesService.CreateNeatSave( + string.Join(";", movedItems), // Store all source paths + DestinationPath, + description + ); + + if (neatSaveSuccess) + { + var neatSavesDialog = new NeatSavesManagementDialog(_neatSavesService); + await neatSavesDialog.ShowAsync(); + } + else + { + MessageBox.Show( + "Files were moved successfully but creating NeatSave backup failed.\n\n" + + "Possible causes:\n" + + "• Insufficient disk space in NeatSaves location\n" + + "• No write permissions to NeatSaves folder\n" + + "• NeatSaves folder path is invalid\n\n" + + "You can check the NeatSaves settings in Settings > NeatSaves Options", + "Warning", + MessageBoxButton.OK, + MessageBoxImage.Warning + ); + } + } + catch (Exception ex) + { + MessageBox.Show( + $"Files were moved successfully but creating NeatSave backup failed.\n\n" + + $"Error details: {ex.Message}\n\n" + + "You can check the NeatSaves settings in Settings > NeatSaves Options", + "Warning", + MessageBoxButton.OK, + MessageBoxImage.Warning + ); + } + } + + // Clear source items after successful operation + SourceItems.Clear(); + } + else + { + StatusMessage = "Operation failed"; + ProgressValue = 0; + } + } + catch (Exception ex) + { + StatusMessage = $"Error: {ex.Message}"; + ProgressValue = 0; + MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); + } + finally + { + IsOperationInProgress = false; + } + } + + [RelayCommand] + private async Task ManageNeatSaves() + { + var dialog = new NeatSavesManagementDialog(_neatSavesService); + await dialog.ShowAsync(); + } + + [RelayCommand] + private void ChangeSafetyOptions() + { + var safetyDialog = new SafetyChoiceDialog(); + if (safetyDialog.ShowDialog() == true) + { + var settings = _settingsService.LoadSettings(); + settings.UseNeatSaves = safetyDialog.ViewModel.UseNeatSavesOnly || safetyDialog.ViewModel.UseBoth; + settings.CreateRestorePoint = safetyDialog.ViewModel.UseSystemRestoreOnly || safetyDialog.ViewModel.UseBoth; + + if (safetyDialog.ViewModel.RememberChoice) + { + settings.HasShownSafetyChoice = true; + } + + _settingsService.SaveSettings(settings); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/ViewModels/NeatSavesManagementViewModel.cs b/NeatShift/NeatShift/ViewModels/NeatSavesManagementViewModel.cs new file mode 100644 index 0000000..77bc0b5 --- /dev/null +++ b/NeatShift/NeatShift/ViewModels/NeatSavesManagementViewModel.cs @@ -0,0 +1,130 @@ +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using NeatShift.Services; +using System.Windows; + +namespace NeatShift.ViewModels +{ + public partial class NeatSavesManagementViewModel : ObservableObject + { + private readonly INeatSavesService _neatSavesService; + private readonly string _operationId; + + [ObservableProperty] + private string _sourcePath; + + [ObservableProperty] + private string _destinationPath; + + public NeatSavesManagementViewModel(INeatSavesService neatSavesService, string operationId, string sourcePath, string destinationPath) + { + _neatSavesService = neatSavesService; + _operationId = operationId; + _sourcePath = sourcePath; + _destinationPath = destinationPath; + } + + [RelayCommand] + private async Task RestoreFiles() + { + var result = MessageBox.Show( + "Are you sure you want to restore the files to their original location? This will overwrite any existing files.", + "Confirm Restore", + MessageBoxButton.YesNo, + MessageBoxImage.Warning + ); + + if (result == MessageBoxResult.Yes) + { + var (success, operationId) = await _neatSavesService.RestoreNeatSave(_operationId); + if (success) + { + MessageBox.Show( + "Files restored successfully.", + "Success", + MessageBoxButton.OK, + MessageBoxImage.Information + ); + + // Prompt to delete the NeatSave + var deleteResult = MessageBox.Show( + "Would you like to delete this NeatSave now that files have been restored?", + "Delete NeatSave", + MessageBoxButton.YesNo, + MessageBoxImage.Question + ); + + if (deleteResult == MessageBoxResult.Yes) + { + bool deleteSuccess = await _neatSavesService.DeleteNeatSave(operationId); + if (deleteSuccess) + { + MessageBox.Show( + "NeatSave deleted successfully.", + "Success", + MessageBoxButton.OK, + MessageBoxImage.Information + ); + } + } + } + else + { + MessageBox.Show( + "Failed to restore files. Please try again.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error + ); + } + } + } + + [RelayCommand] + private async Task DeleteBackup() + { + var result = MessageBox.Show( + "Are you sure you want to delete this backup? This action cannot be undone.", + "Confirm Delete", + MessageBoxButton.YesNo, + MessageBoxImage.Warning + ); + + if (result == MessageBoxResult.Yes) + { + bool success = await _neatSavesService.DeleteNeatSave(_operationId); + if (success) + { + MessageBox.Show( + "Backup deleted successfully.", + "Success", + MessageBoxButton.OK, + MessageBoxImage.Information + ); + } + else + { + MessageBox.Show( + "Failed to delete backup. Please try again.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error + ); + } + } + } + + [RelayCommand] + private void ManageNeatSaves() + { + // TODO: Implement NeatSaves management dialog + MessageBox.Show( + "NeatSaves management coming soon!", + "Information", + MessageBoxButton.OK, + MessageBoxImage.Information + ); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/ViewModels/RestorePointViewModel.cs b/NeatShift/NeatShift/ViewModels/RestorePointViewModel.cs new file mode 100644 index 0000000..1ac785f --- /dev/null +++ b/NeatShift/NeatShift/ViewModels/RestorePointViewModel.cs @@ -0,0 +1,270 @@ +// NeatShift - Easily move files while keeping them accessible +// Copyright (C) 2024 BytexGrid +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Threading.Tasks; +using System.Windows; +using System.Linq; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using NeatShift.Models; + +namespace NeatShift.ViewModels +{ + public partial class RestorePointViewModel : ObservableObject + { + private readonly Services.ISystemRestoreService _systemRestoreService; + + [ObservableProperty] + private ObservableCollection _restorePoints = new(); + + private string _statusMessage = string.Empty; + public string StatusMessage + { + get => _statusMessage; + set + { + if (SetProperty(ref _statusMessage, value)) + { + OnPropertyChanged(nameof(HasStatusMessage)); + } + } + } + + [ObservableProperty] + private bool _isLoading = false; + + public bool HasStatusMessage => !string.IsNullOrEmpty(StatusMessage); + + public bool HasRestorePoints => RestorePoints.Count > 0; + + public RestorePointViewModel() + { + _systemRestoreService = new Services.SystemRestoreService(); + LoadRestorePointsAsync().ConfigureAwait(false); + } + + [RelayCommand] + private async Task Refresh() + { + IsLoading = true; + try + { + await LoadRestorePointsAsync(); + } + finally + { + IsLoading = false; + } + } + + private async Task LoadRestorePointsAsync() + { + try + { + var points = await _systemRestoreService.GetRestorePoints(); + RestorePoints.Clear(); + foreach (var point in points.OrderByDescending(p => p.CreationTime)) + { + RestorePoints.Add(point); + } + + if (RestorePoints.Count == 0) + { + StatusMessage = "No restore points found. Click the 'Create New Restore Point' button above."; + } + else + { + StatusMessage = string.Empty; + } + + OnPropertyChanged(nameof(HasRestorePoints)); + } + catch (Exception ex) + { + Debug.WriteLine($"Error loading restore points: {ex.Message}"); + StatusMessage = "Could not load restore points. Please run as administrator."; + } + } + + [RelayCommand] + private async Task CreateRestorePoint() + { + IsLoading = true; + StatusMessage = string.Empty; + + try + { + // Get current points before trying to create + var beforePoints = await _systemRestoreService.GetRestorePoints(); + var success = await _systemRestoreService.CreateRestorePoint("Manual restore point from NeatShift"); + + if (!success) + { + // Get points again to check if any were created in the last 3 minutes + var afterPoints = await _systemRestoreService.GetRestorePoints(); + var recentPoint = afterPoints.FirstOrDefault(); + var timeSinceLastPoint = recentPoint != null ? + (DateTime.Now - recentPoint.CreationTime).TotalMinutes : + double.MaxValue; + + if (timeSinceLastPoint < 3) + { + StatusMessage = "Please wait at least 3 minutes between creating restore points. " + + "This limit helps prevent system resource abuse."; + } + else + { + StatusMessage = "Failed to create restore point. Please ensure:\n" + + "1. NeatShift is running as administrator\n" + + "2. System Protection is enabled\n" + + "3. You have enough disk space"; + } + } + else + { + await Refresh(); + } + } + catch (Exception ex) + { + Debug.WriteLine($"Error creating restore point: {ex.Message}"); + StatusMessage = "An unexpected error occurred while creating the restore point."; + } + finally + { + IsLoading = false; + } + } + + [RelayCommand] + private void OpenSystemProtection() + { + try + { + Process.Start(new ProcessStartInfo + { + FileName = "SystemPropertiesProtection.exe", + UseShellExecute = true, + Verb = "runas" // Request admin privileges + }); + } + catch (Exception ex) + { + Debug.WriteLine($"Error opening System Protection: {ex.Message}"); + MessageBox.Show( + "Could not open System Protection settings. Please open Windows Settings and search for 'System Protection'.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + } + + [RelayCommand] + private async Task RestoreToPoint(RestorePoint point) + { + var result = MessageBox.Show( + "Are you sure you want to restore your system to this point? Your computer will restart.", + "Confirm System Restore", + MessageBoxButton.YesNo, + MessageBoxImage.Warning); + + if (result == MessageBoxResult.Yes) + { + try + { + await Task.Run(() => + { + // Launch the system restore UI with admin privileges + Process.Start(new ProcessStartInfo + { + FileName = "rstrui.exe", + UseShellExecute = true, + Verb = "runas" + }); + }); + } + catch (Exception ex) + { + Debug.WriteLine($"Error starting system restore: {ex.Message}"); + MessageBox.Show( + "Could not start System Restore. Please ensure you have administrator privileges.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + } + } + + [RelayCommand] + private async Task DeleteRestorePoint(RestorePoint point) + { + var result = MessageBox.Show( + "Are you sure you want to delete this restore point? This cannot be undone.", + "Confirm Delete", + MessageBoxButton.YesNo, + MessageBoxImage.Warning); + + if (result == MessageBoxResult.Yes) + { + IsLoading = true; + try + { + bool success = await _systemRestoreService.DeleteRestorePoint(point.Id); + if (success) + { + Application.Current.Dispatcher.Invoke(() => + { + RestorePoints.Remove(point); + }); + + MessageBox.Show( + "Restore point deleted successfully.", + "Success", + MessageBoxButton.OK, + MessageBoxImage.Information); + + await Refresh(); // Refresh the list to ensure it's up to date + } + else + { + MessageBox.Show( + "Could not delete restore point. Please ensure you have administrator privileges.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + } + catch (Exception ex) + { + Debug.WriteLine($"Error deleting restore point: {ex.Message}"); + Debug.WriteLine($"Stack trace: {ex.StackTrace}"); + MessageBox.Show( + "Could not delete restore point. Please ensure you have administrator privileges.", + "Error", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + finally + { + IsLoading = false; + } + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/ViewModels/SafetyChoiceViewModel.cs b/NeatShift/NeatShift/ViewModels/SafetyChoiceViewModel.cs new file mode 100644 index 0000000..9ab870a --- /dev/null +++ b/NeatShift/NeatShift/ViewModels/SafetyChoiceViewModel.cs @@ -0,0 +1,46 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace NeatShift.ViewModels +{ + public partial class SafetyChoiceViewModel : ObservableObject + { + [ObservableProperty] + private bool _useNeatSavesOnly; + + [ObservableProperty] + private bool _useSystemRestoreOnly; + + [ObservableProperty] + private bool _useBoth = true; // Default choice + + [ObservableProperty] + private bool _rememberChoice; + + partial void OnUseNeatSavesOnlyChanged(bool value) + { + if (value) + { + UseSystemRestoreOnly = false; + UseBoth = false; + } + } + + partial void OnUseSystemRestoreOnlyChanged(bool value) + { + if (value) + { + UseNeatSavesOnly = false; + UseBoth = false; + } + } + + partial void OnUseBothChanged(bool value) + { + if (value) + { + UseNeatSavesOnly = false; + UseSystemRestoreOnly = false; + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToAccentConverter.cs b/NeatShift/NeatShift/Views/BooleanToAccentConverter.cs new file mode 100644 index 0000000..2756475 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToAccentConverter.cs @@ -0,0 +1,21 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace NeatShift.Converters +{ + public class BooleanToAccentConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value + ? System.Windows.Application.Current.Resources["SystemAccentBrush"] + : System.Windows.Application.Current.Resources["SystemControlForegroundBaseMediumHighBrush"]; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToArrowConverter.cs b/NeatShift/NeatShift/Views/BooleanToArrowConverter.cs new file mode 100644 index 0000000..dbc8864 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToArrowConverter.cs @@ -0,0 +1,21 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace NeatShift.Views +{ + public class BooleanToArrowConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value + ? "M0,4 L8,4 L4,0 Z" // Up arrow + : "M0,0 L8,0 L4,4 Z"; // Down arrow + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToGlyphConverter.cs b/NeatShift/NeatShift/Views/BooleanToGlyphConverter.cs new file mode 100644 index 0000000..600b2a2 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToGlyphConverter.cs @@ -0,0 +1,27 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace NeatShift.Views +{ + public class BooleanToGlyphConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue && parameter is string glyphs) + { + var parts = glyphs.Split(','); + if (parts.Length == 2) + { + return boolValue ? parts[1] : parts[0]; + } + } + return string.Empty; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToNumberConverter.cs b/NeatShift/NeatShift/Views/BooleanToNumberConverter.cs new file mode 100644 index 0000000..0429b99 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToNumberConverter.cs @@ -0,0 +1,19 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace NeatShift.Views +{ + public class BooleanToNumberConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? 0 : 1; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (int)value == 0; + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToSelectionModeConverter.cs b/NeatShift/NeatShift/Views/BooleanToSelectionModeConverter.cs new file mode 100644 index 0000000..1030460 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToSelectionModeConverter.cs @@ -0,0 +1,20 @@ +using System; +using System.Globalization; +using System.Windows.Controls; +using System.Windows.Data; + +namespace NeatShift.Converters +{ + public class BooleanToSelectionModeConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? SelectionMode.Multiple : SelectionMode.Single; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return (SelectionMode)value == SelectionMode.Multiple; + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToSymbolConverter.cs b/NeatShift/NeatShift/Views/BooleanToSymbolConverter.cs new file mode 100644 index 0000000..04ee56c --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToSymbolConverter.cs @@ -0,0 +1,28 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using ModernWpf.Controls; + +namespace NeatShift.Views +{ + public class BooleanToSymbolConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue && parameter is string symbols) + { + var parts = symbols.Split(','); + if (parts.Length == 2) + { + return Enum.Parse(typeof(Symbol), boolValue ? parts[1] : parts[0]); + } + } + return Symbol.Add; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToViewIconConverter.cs b/NeatShift/NeatShift/Views/BooleanToViewIconConverter.cs new file mode 100644 index 0000000..6db64e4 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToViewIconConverter.cs @@ -0,0 +1,20 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows; + +namespace NeatShift.Views +{ + public class BooleanToViewIconConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? "\uF0E2" : "\uEA37"; // GridView : List + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/BooleanToVisibilityConverter.cs b/NeatShift/NeatShift/Views/BooleanToVisibilityConverter.cs new file mode 100644 index 0000000..74a76c9 --- /dev/null +++ b/NeatShift/NeatShift/Views/BooleanToVisibilityConverter.cs @@ -0,0 +1,33 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace NeatShift.Views +{ + public class BooleanToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? Visibility.Visible : Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + public class BooleanToInverseVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? Visibility.Collapsed : Visibility.Visible; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/ContactDialog.xaml b/NeatShift/NeatShift/Views/ContactDialog.xaml new file mode 100644 index 0000000..a67b6a8 --- /dev/null +++ b/NeatShift/NeatShift/Views/ContactDialog.xaml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + Reddit + + + + + + + + + + + Telegram + + + + + + + + + + + Discord + + + + \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/ContactDialog.xaml.cs b/NeatShift/NeatShift/Views/ContactDialog.xaml.cs new file mode 100644 index 0000000..b57f900 --- /dev/null +++ b/NeatShift/NeatShift/Views/ContactDialog.xaml.cs @@ -0,0 +1,37 @@ +using System.Diagnostics; +using System.Windows; +using ModernWpf.Controls; + +namespace NeatShift.Views +{ + public partial class ContactDialog : ContentDialog + { + // These will be replaced with actual links later + private const string REDDIT_LINK = ""; // Temporarily removed as community is being set up + private const string TELEGRAM_LINK = "https://t.me/NeatShift"; + private const string DISCORD_LINK = "https://discord.gg/tc3AjBRQq9"; + + public ContactDialog() + { + InitializeComponent(); + } + + private void Reddit_Click(object sender, RoutedEventArgs e) + { + MessageBox.Show("Reddit community is currently being set up. Please check back later.", + "Coming Soon", + MessageBoxButton.OK, + MessageBoxImage.Information); + } + + private void Telegram_Click(object sender, RoutedEventArgs e) + { + Process.Start(new ProcessStartInfo { FileName = TELEGRAM_LINK, UseShellExecute = true }); + } + + private void Discord_Click(object sender, RoutedEventArgs e) + { + Process.Start(new ProcessStartInfo { FileName = DISCORD_LINK, UseShellExecute = true }); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/FeatureRequestDialog.xaml b/NeatShift/NeatShift/Views/FeatureRequestDialog.xaml new file mode 100644 index 0000000..b620177 --- /dev/null +++ b/NeatShift/NeatShift/Views/FeatureRequestDialog.xaml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/FeatureRequestDialog.xaml.cs b/NeatShift/NeatShift/Views/FeatureRequestDialog.xaml.cs new file mode 100644 index 0000000..ff36bfa --- /dev/null +++ b/NeatShift/NeatShift/Views/FeatureRequestDialog.xaml.cs @@ -0,0 +1,39 @@ +using System; +using System.Diagnostics; +using ModernWpf.Controls; + +namespace NeatShift.Views +{ + public partial class FeatureRequestDialog : ContentDialog + { + public FeatureRequestDialog() + { + InitializeComponent(); + this.PrimaryButtonClick += FeatureRequestDialog_PrimaryButtonClick; + } + + private void FeatureRequestDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) + { + // Get a deferral because we're going to do an async operation + var deferral = args.GetDeferral(); + + try + { + // Create GitHub issue URL with pre-filled content + var title = Uri.EscapeDataString(TitleTextBox.Text); + var description = Uri.EscapeDataString( + $"{DescriptionTextBox.Text}\n\n" + + $"**Use Case:**\n{UseCaseTextBox.Text}"); + + var url = $"https://github.com/BytexGrid/NeatShift/issues/new?title={title}&body={description}&labels=enhancement"; + + // Open in browser + Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true }); + } + finally + { + deferral.Complete(); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/FileBrowserControl.xaml b/NeatShift/NeatShift/Views/FileBrowserControl.xaml new file mode 100644 index 0000000..69d1a48 --- /dev/null +++ b/NeatShift/NeatShift/Views/FileBrowserControl.xaml @@ -0,0 +1,493 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/FileBrowserControl.xaml.cs b/NeatShift/NeatShift/Views/FileBrowserControl.xaml.cs new file mode 100644 index 0000000..5178635 --- /dev/null +++ b/NeatShift/NeatShift/Views/FileBrowserControl.xaml.cs @@ -0,0 +1,203 @@ +using System; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows; +using NeatShift.ViewModels; +using Microsoft.Extensions.DependencyInjection; +using System.Linq; +using System.Windows.Data; + +namespace NeatShift.Views +{ + public partial class FileBrowserControl : UserControl + { + private Point _startPoint; + private FileBrowserViewModel ViewModel => (FileBrowserViewModel)DataContext; + + public FileBrowserControl() + { + InitializeComponent(); + DataContext = ((App)App.Current).Services.GetRequiredService(); + + // Enable drag on the ListView + FileListView.PreviewMouseLeftButtonDown += FileListView_PreviewMouseLeftButtonDown; + FileListView.PreviewMouseMove += FileListView_PreviewMouseMove; + FileListView.PreviewMouseLeftButtonUp += FileListView_PreviewMouseLeftButtonUp; + + // Add key handlers to both views + FileListView.PreviewKeyDown += ListView_KeyDown; + this.PreviewKeyDown += ListView_KeyDown; // Handle keys at UserControl level + } + + private void FileListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + _startPoint = e.GetPosition(null); + } + + private void FileListView_PreviewMouseMove(object sender, MouseEventArgs e) + { + if (e.LeftButton == MouseButtonState.Pressed && + ViewModel != null && + ViewModel.CanDragItems) + { + var paths = ViewModel.GetDragPaths().ToArray(); + if (paths.Length > 0) + { + var data = new DataObject(DataFormats.FileDrop, paths); + DragDrop.DoDragDrop(FileListView, data, DragDropEffects.Copy | DragDropEffects.Move); + } + } + } + + private void FileListView_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) + { + // No longer need to track dragging state + } + + private void StartDrag() + { + if (ViewModel != null) + { + var selectedItems = ViewModel.SelectedItems.ToList(); + if (selectedItems.Count > 0) + { + var filePaths = selectedItems.Select(item => item.Path).ToArray(); + var dataObject = new DataObject(DataFormats.FileDrop, filePaths); + DragDrop.DoDragDrop(FileListView, dataObject, DragDropEffects.Copy); + } + } + } + + private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + if (ViewModel != null) + { + ViewModel.ItemDoubleClickCommand.Execute(null); + } + } + + private void ListView_KeyDown(object sender, KeyEventArgs e) + { + if (ViewModel != null) + { + if (e.Key == Key.Enter) + { + e.Handled = true; + ViewModel.ItemDoubleClickCommand.Execute(null); + } + else if (e.Key == Key.A && Keyboard.Modifiers == ModifierKeys.Control) + { + e.Handled = true; + ViewModel.HandleKeyDown("A", true); + } + } + } + + private void ColumnHeader_Click(object sender, MouseButtonEventArgs e) + { + if (sender is TextBlock textBlock && ViewModel != null) + { + ViewModel.SortCommand.Execute(textBlock.Tag?.ToString()); + } + } + + private void PathTextBox_KeyDown(object sender, KeyEventArgs e) + { + if (ViewModel != null) + { + if (e.Key == Key.Enter || e.Key == Key.Escape) + { + e.Handled = true; + ViewModel.HandlePathKeyDown(e.Key.ToString()); + } + } + } + + private void Breadcrumb_MouseDown(object sender, MouseButtonEventArgs e) + { + // Only handle clicks on the background, not on the buttons + if (e.Source is Border && ViewModel != null) + { + ViewModel.IsEditingPath = true; + e.Handled = true; + + // Focus the TextBox and select all text + PathTextBox.Focus(); + PathTextBox.SelectAll(); + } + } + + private void QuickAccess_Click(object sender, RoutedEventArgs e) + { + if (sender is Button button && button.ContextMenu != null && ViewModel != null) + { + // Clear existing location items + var menu = button.ContextMenu; + var itemsToRemove = menu.Items.Cast() + .Where(item => item is MenuItem menuItem && + menuItem.Header?.ToString() != "Recent Locations" && + menuItem.Header?.ToString() != "Clear Recent Locations") + .ToList(); + + foreach (var item in itemsToRemove) + { + menu.Items.Remove(item); + } + + // Add recent locations after the header + var headerIndex = menu.Items.Cast() + .TakeWhile(item => item is MenuItem menuItem && + menuItem.Header?.ToString() != "Recent Locations") + .Count(); + + var insertIndex = headerIndex + 2; // After header and separator + + foreach (var location in ViewModel.RecentLocations) + { + var menuItem = new MenuItem + { + Header = location, + Command = ViewModel.NavigateToPathCommand, + CommandParameter = location + }; + + var icon = new TextBlock + { + Text = "\uE8DA", + FontFamily = new System.Windows.Media.FontFamily("Segoe MDL2 Assets"), + FontSize = 14, + Foreground = System.Windows.Application.Current.Resources["SystemControlForegroundBaseMediumBrush"] as System.Windows.Media.Brush + }; + System.Windows.Automation.AutomationProperties.SetName(icon, "Folder Icon"); + + menuItem.Icon = icon; + menu.Items.Insert(insertIndex++, menuItem); + } + + button.ContextMenu.IsOpen = true; + } + } + + private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (ViewModel != null && ViewModel.IsSelectionMode) + { + System.Diagnostics.Debug.WriteLine($"Selection changed - Added: {e.AddedItems.Count}, Removed: {e.RemovedItems.Count}"); + ViewModel.SelectedItems.Clear(); + foreach (FileItem item in FileListView.SelectedItems) + { + ViewModel.SelectedItems.Add(item); + } + System.Diagnostics.Debug.WriteLine($"Total selected items: {ViewModel.SelectedItems.Count}"); + } + } + + private void SelectAllItems() + { + if (ViewModel != null) + { + ViewModel.SelectAll(); + } + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/GuideStep.cs b/NeatShift/NeatShift/Views/GuideStep.cs new file mode 100644 index 0000000..91b526e --- /dev/null +++ b/NeatShift/NeatShift/Views/GuideStep.cs @@ -0,0 +1,22 @@ +using System; + +namespace NeatShift.Views +{ + public class GuideStep + { + public int Number { get; set; } + public string Title { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + + public GuideStep() + { + } + + public GuideStep(int number, string title, string description) + { + Number = number; + Title = title ?? throw new ArgumentNullException(nameof(title)); + Description = description ?? throw new ArgumentNullException(nameof(description)); + } + } +} \ No newline at end of file diff --git a/NeatShift/NeatShift/Views/MainWindow.xaml b/NeatShift/NeatShift/Views/MainWindow.xaml new file mode 100644 index 0000000..e0b5e36 --- /dev/null +++ b/NeatShift/NeatShift/Views/MainWindow.xaml @@ -0,0 +1,478 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + symbolic links + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + Select Destination + Choose where you want to move your files. Use Browse or switch to NeatExplorer for easier navigation. + + + 2 + Add Files + Use the 'Add Files' or 'Add Folder' buttons to select items. You can also drag and drop files directly. + + + 3 + Review and Move + Check your selection and click 'Move'. NeatShift will create symbolic links and handle backups automatically. + + + + + + + + + + + + + + + + + + + + Use 'View Links' to manage existing symbolic links + Switch to NeatExplorer for advanced file browsing + Enable both backup options for maximum safety + Dark/Light theme automatically adapts to your Windows settings + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +