Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FileViewer: ViewMode to track what is currently displayed #8496

Merged
1 commit merged into from
Oct 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion GitUI/CommandsDialogs/FormVerify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public FormVerify([NotNull] GitUICommands commands)
columnParent.MinimumWidth = DpiUtil.Scale(75);

_selectedItemsHeader.AttachTo(columnIsLostObjectSelected);
fileViewer.ExtraDiffArgumentsChanged += Warnings_SelectionChanged;

InitializeComplete();
Warnings.AutoGenerateColumns = false;
Expand Down Expand Up @@ -243,7 +244,7 @@ private void Warnings_SelectionChanged(object sender, EventArgs e)
if (_previewedItem.ObjectType == LostObjectType.Commit)
{
ThreadHelper.JoinableTaskFactory.RunAsync(() =>
fileViewer.ViewPatchAsync("commit.patch", content, null))
fileViewer.ViewFixedPatchAsync("commit.patch", content, null))
.FileAndForget();
}
else
Expand Down
3 changes: 2 additions & 1 deletion GitUI/CommandsDialogs/FormViewPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public FormViewPatch(GitUICommands commands)

typeDataGridViewTextBoxColumn.Width = DpiUtil.Scale(70);
File.Width = DpiUtil.Scale(50);
ChangesList.ExtraDiffArgumentsChanged += GridChangedFiles_SelectionChanged;

InitializeComplete();

Expand Down Expand Up @@ -55,7 +56,7 @@ private void GridChangedFiles_SelectionChanged(object sender, EventArgs e)
return;
}

ChangesList.ViewPatch(patch.FileNameB, patch.Text ?? "");
ChangesList.ViewFixedPatch(patch.FileNameB, patch.Text ?? "");
}

private void BrowsePatch_Click(object sender, EventArgs e)
Expand Down
3 changes: 2 additions & 1 deletion GitUI/CommandsDialogs/RepoHosting/ViewPullRequestsForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ private ViewPullRequestsForm(GitUICommands commands)
{
InitializeComponent();
_selectHostedRepoCB.DisplayMember = nameof(IHostedRemote.DisplayData);
_diffViewer.ExtraDiffArgumentsChanged += _fileStatusList_SelectedIndexChanged;
_loader.LoadingError += (sender, ex) =>
{
MessageBox.Show(this, ex.Exception.ToString(), Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
Expand Down Expand Up @@ -494,7 +495,7 @@ private void _fileStatusList_SelectedIndexChanged(object sender, EventArgs e)
}
else
{
_diffViewer.ViewPatch(gis.Name, text: data);
_diffViewer.ViewFixedPatch(gis.Name, text: data);
}
}

Expand Down
186 changes: 109 additions & 77 deletions GitUI/Editor/FileViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,24 @@ public partial class FileViewer : GitModuleControl
/// </summary>
public event Action EscapePressed;

/// <summary>
/// The type of information currently shown in the file viewer
/// </summary>
private enum ViewMode
{
// Plain text
Text,

// Diff or patch
Diff,

// Diffs that will not be affected by diff arguments like white space etc (limited options)
FixedDiff,
gerhardol marked this conversation as resolved.
Show resolved Hide resolved

// Image viewer
Image
}

private readonly TranslationString _largeFileSizeWarning = new TranslationString("This file is {0:N1} MB. Showing large files can be slow. Click to show anyway.");
private readonly TranslationString _cannotViewImage = new TranslationString("Cannot view image {0}");

Expand All @@ -48,8 +66,7 @@ public partial class FileViewer : GitModuleControl

private readonly AsyncLoader _async;
private readonly IFullPathResolver _fullPathResolver;
private bool _currentViewIsPatch;
private bool _patchHighlighting;
private ViewMode _viewMode;
private Encoding _encoding;
private Func<Task> _deferShowFunc;
private readonly ContinuousScrollEventManager _continuousScrollEventManager;
Expand Down Expand Up @@ -83,7 +100,7 @@ public FileViewer()
{
if (!IsDisposed)
{
ResetForText(null);
ResetView(ViewMode.Text, null);
internalFileViewer.SetText("Unsupported file: \n\n" + e.Exception.ToString(), openWithDifftool: null /* not applicable */);
TextLoaded?.Invoke(this, null);
}
Expand Down Expand Up @@ -124,7 +141,7 @@ public FileViewer()

internalFileViewer.MouseMove += (_, e) =>
{
if (_currentViewIsPatch && !fileviewerToolbar.Visible)
if (IsDiffView(_viewMode) && !fileviewerToolbar.Visible)
{
fileviewerToolbar.Visible = true;
fileviewerToolbar.Location = new Point(Width - fileviewerToolbar.Width - 40, 0);
Expand All @@ -141,7 +158,7 @@ public FileViewer()
};
internalFileViewer.TextChanged += (sender, e) =>
{
if (_patchHighlighting)
if (IsDiffView(_viewMode))
{
internalFileViewer.AddPatchHighlighting();
}
Expand Down Expand Up @@ -431,16 +448,26 @@ public void ViewCurrentChanges(GitItemStatus item, bool isStaged, [CanBeNull] Ac

public async Task ViewPatchAsync(string fileName, string text, Action openWithDifftool)
{
await ShowOrDeferAsync(
text.Length,
() =>
{
ResetForDiff(fileName);
internalFileViewer.SetText(text, openWithDifftool, isDiff: true);
await ViewPrivateAsync(fileName, text, openWithDifftool, ViewMode.Diff);
}

TextLoaded?.Invoke(this, null);
return Task.CompletedTask;
});
/// <summary>
/// Present the text as a patch in the file viewer, for GitHub
/// </summary>
/// <param name="fileName">The fileName to present</param>
/// <param name="text">The patch text</param>
/// <param name="openWithDifftool">The action to open the difftool</param>
public void ViewFixedPatch([CanBeNull] string fileName,
[NotNull] string text,
[CanBeNull] Action openWithDifftool = null)
{
ThreadHelper.JoinableTaskFactory.Run(
() => ViewPrivateAsync(fileName, text, openWithDifftool, ViewMode.FixedDiff));
}

public async Task ViewFixedPatchAsync(string fileName, string text, Action openWithDifftool = null)
{
await ViewPrivateAsync(fileName, text, openWithDifftool, ViewMode.FixedDiff);
}

public void ViewText([CanBeNull] string fileName,
Expand All @@ -458,7 +485,7 @@ public async Task ViewPatchAsync(string fileName, string text, Action openWithDi
text.Length,
() =>
{
ResetForText(fileName);
ResetView(ViewMode.Text, fileName);

// Check for binary file. Using gitattributes could be misleading for a changed file,
// but not much other can be done
Expand Down Expand Up @@ -726,6 +753,25 @@ void DetectDefaultEncoding()

// Private methods

private static bool IsDiffView(ViewMode viewMode)
{
return viewMode == ViewMode.Diff || viewMode == ViewMode.FixedDiff;
}

private async Task ViewPrivateAsync(string fileName, string text, Action openWithDifftool, ViewMode viewMode = ViewMode.Diff)
RussKie marked this conversation as resolved.
Show resolved Hide resolved
{
await ShowOrDeferAsync(
text.Length,
() =>
{
ResetView(viewMode, fileName);
internalFileViewer.SetText(text, openWithDifftool, isDiff: IsDiffView(_viewMode));

TextLoaded?.Invoke(this, null);
return Task.CompletedTask;
});
}

private void CopyNotStartingWith(char startChar)
{
string code = internalFileViewer.GetSelectedText();
Expand All @@ -737,7 +783,7 @@ private void CopyNotStartingWith(char startChar)
noSelection = true;
}

if (_currentViewIsPatch)
if (IsDiffView(_viewMode))
{
// add artificial space if selected text is not starting from line beginning, it will be removed later
int pos = noSelection ? 0 : internalFileViewer.GetSelectionPosition();
Expand Down Expand Up @@ -765,27 +811,38 @@ private void CopyNotStartingWith(char startChar)
ClipboardUtil.TrySetText(code.AdjustLineEndings(Module.EffectiveConfigFile.core.autocrlf.Value));
}

private void SetVisibilityDiffContextMenu(bool visibleTextFile, [CanBeNull] string fileName)
{
_currentViewIsPatch = visibleTextFile;
ignoreWhitespaceAtEolToolStripMenuItem.Visible = visibleTextFile;
ignoreWhitespaceChangesToolStripMenuItem.Visible = visibleTextFile;
ignoreAllWhitespaceChangesToolStripMenuItem.Visible = visibleTextFile;
increaseNumberOfLinesToolStripMenuItem.Visible = visibleTextFile;
decreaseNumberOfLinesToolStripMenuItem.Visible = visibleTextFile;
showEntireFileToolStripMenuItem.Visible = visibleTextFile;
toolStripSeparator2.Visible = visibleTextFile;
treatAllFilesAsTextToolStripMenuItem.Visible = visibleTextFile;
copyNewVersionToolStripMenuItem.Visible = visibleTextFile;
copyOldVersionToolStripMenuItem.Visible = visibleTextFile;

bool fileExists = !string.IsNullOrWhiteSpace(fileName)
&& File.Exists(_fullPathResolver.Resolve(fileName));

cherrypickSelectedLinesToolStripMenuItem.Visible =
revertSelectedLinesToolStripMenuItem.Visible =
visibleTextFile && fileExists && !Module.IsBareRepository();
copyPatchToolStripMenuItem.Visible = visibleTextFile;
private void SetVisibilityDiffContextMenu(ViewMode viewMode, [CanBeNull] string fileName)
{
bool changePhysicalFile = (viewMode == ViewMode.Diff || viewMode == ViewMode.FixedDiff)
&& !Module.IsBareRepository()
&& !string.IsNullOrWhiteSpace(fileName)
&& File.Exists(_fullPathResolver.Resolve(fileName));

cherrypickSelectedLinesToolStripMenuItem.Visible = changePhysicalFile;
revertSelectedLinesToolStripMenuItem.Visible = changePhysicalFile;
copyPatchToolStripMenuItem.Visible = IsDiffView(viewMode);
copyNewVersionToolStripMenuItem.Visible = IsDiffView(viewMode);
copyOldVersionToolStripMenuItem.Visible = IsDiffView(viewMode);

ignoreWhitespaceAtEolToolStripMenuItem.Visible = viewMode == ViewMode.Diff;
ignoreWhitespaceChangesToolStripMenuItem.Visible = viewMode == ViewMode.Diff;
ignoreAllWhitespaceChangesToolStripMenuItem.Visible = viewMode == ViewMode.Diff;
increaseNumberOfLinesToolStripMenuItem.Visible = viewMode == ViewMode.Diff;
decreaseNumberOfLinesToolStripMenuItem.Visible = viewMode == ViewMode.Diff;
showEntireFileToolStripMenuItem.Visible = viewMode == ViewMode.Diff;
toolStripSeparator2.Visible = IsDiffView(viewMode);
treatAllFilesAsTextToolStripMenuItem.Visible = IsDiffView(viewMode);

// toolbar
nextChangeButton.Visible = IsDiffView(viewMode);
previousChangeButton.Visible = IsDiffView(viewMode);
increaseNumberOfLines.Visible = viewMode == ViewMode.Diff;
decreaseNumberOfLines.Visible = viewMode == ViewMode.Diff;
showEntireFileButton.Visible = viewMode == ViewMode.Diff;
showSyntaxHighlighting.Visible = IsDiffView(viewMode);
ignoreWhitespaceAtEol.Visible = viewMode == ViewMode.Diff;
ignoreWhiteSpaces.Visible = viewMode == ViewMode.Diff;
ignoreAllWhitespaces.Visible = viewMode == ViewMode.Diff;
}

private void SetVisibilityDiffContextMenuStaging()
Expand Down Expand Up @@ -915,55 +972,30 @@ private void OnIgnoreWhitespaceChanged()
AppSettings.IgnoreWhitespaceKind = IgnoreWhitespace;
}

private void ResetForImage([CanBeNull] string fileName)
{
Reset(false, false, fileName);
internalFileViewer.SetHighlighting("Default");
}

private void ResetForText([CanBeNull] string fileName)
private void ResetView(ViewMode viewMode, [CanBeNull] string fileName)
{
if (!string.IsNullOrEmpty(fileName) &&
(fileName.EndsWith(".diff", StringComparison.OrdinalIgnoreCase) ||
fileName.EndsWith(".patch", StringComparison.OrdinalIgnoreCase)))
_viewMode = viewMode;
if (_viewMode == ViewMode.Text
&& !string.IsNullOrEmpty(fileName)
&& (fileName.EndsWith(".diff", StringComparison.OrdinalIgnoreCase)
|| fileName.EndsWith(".patch", StringComparison.OrdinalIgnoreCase)))
{
ResetForDiff(fileName);
return;
}

Reset(false, true, fileName);

if (fileName == null)
{
internalFileViewer.SetHighlighting("Default");
}
else
{
internalFileViewer.SetHighlightingForFile(fileName);
_viewMode = ViewMode.FixedDiff;
}
}

private void ResetForDiff([CanBeNull] string fileName)
{
Reset(true, true, fileName);
SetVisibilityDiffContextMenu(_viewMode, fileName);
ClearImage();
PictureBox.Visible = _viewMode == ViewMode.Image;
internalFileViewer.Visible = _viewMode != ViewMode.Image;

if (ShowSyntaxHighlightingInDiff && fileName != null)
if (((ShowSyntaxHighlightingInDiff && IsDiffView(_viewMode)) || _viewMode == ViewMode.Text) && fileName != null)
{
internalFileViewer.SetHighlightingForFile(fileName);
}
else
{
internalFileViewer.SetHighlighting("");
}
}

private void Reset(bool isDiff, bool isText, [CanBeNull] string fileName)
{
_patchHighlighting = isDiff;
SetVisibilityDiffContextMenu(isDiff, fileName);
ClearImage();
PictureBox.Visible = !isText;
internalFileViewer.Visible = isText;

return;

Expand Down Expand Up @@ -999,12 +1031,12 @@ private Task ViewItemAsync(string fileName, bool isSubmodule, Func<Image> getIma
{
if (image == null)
{
ResetForText(null);
ResetView(ViewMode.Text, null);
internalFileViewer.SetText(string.Format(_cannotViewImage.Text, fileName), openWithDifftool);
return;
}

ResetForImage(fileName);
ResetView(ViewMode.Image, fileName);
var size = DpiUtil.Scale(image.Size);
if (size.Height > PictureBox.Size.Height || size.Width > PictureBox.Size.Width)
{
Expand Down Expand Up @@ -1283,7 +1315,7 @@ private void CopyToolStripMenuItemClick(object sender, EventArgs e)
return;
}

if (_currentViewIsPatch)
if (IsDiffView(_viewMode))
{
// add artificial space if selected text is not starting from line beginning, it will be removed later
int pos = internalFileViewer.GetSelectionPosition();
Expand Down